关于json:Php-json_decode返回null

Php - json_decode returns null

我正在尝试使用json_decode php函数解码如下所示的json字符串:

1
"{id:"1",fields:[{id:"1",value:"asdasd"},{id:"2",value:"asdasd"},{id:"3",value:"asdasd"}]}"

我从这个问题中尝试了各种选择。像:

1
2
$foo = utf8_encode($json_string);
$data = json_decode($foo, true);

或:

1
json_decode(str_replace ('"','"', $json_string), true);

即使使用:

1
json_decode( preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $json_string), true );

但是,我尝试的所有内容总是得到null
为什么会这样?


首先,您的JSON无效。在使用任何JSON lint工具进行询问之前,您应该始终先验证JSON,这样才能准确告诉您错误的位置和原因。

此外,在PHP中处理JSON时,您应始终检查错误。您可以查看有关如何正确执行验证的json_last_error函数的官方文档。

1
2
3
4
5
6
7
8
$json = 'your_json_string';
$array = json_decode($json, true);

if (json_last_error()) {
    die('Invalid JSON provided!');
}

printf('[cc lang="php"]Valid JSON output: %s

\\',print_r($ array,true));

值得一提的是:自PHP 7.3起添加了JSON_THROW_ON_ERROR选项,因此可以使用try-catch块将代码包裹起来:

1
2
3
4
5
6
try {
    $array = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    printf('Valid JSON output: %s', print_r($array, true));
} catch (\\JsonException $exception) {
    printf('Invalid JSON input: %s', print_r($exception, true));
}

工作示例。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
$data='{
   "id":"1",
   "fields": [{
       "id":"1",
       "value":"asdasd"
    }, {
       "id":"2",
       "value":"asdasd"
    }, {
       "id":"3",
       "value":"asdasd"
    }]
}'
;

$dataNew=json_decode($data,true);
echo '[cc lang="php"]';
    print_r($dataNew);

您的json无效。 json键必须在双引号内。之后json_decode将正常工作。

输出为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Array
(
    [id] => 1
    [fields] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [value] => asdasd
                )

            [1] => Array
                (
                    [id] => 2
                    [value] => asdasd
                )

            [2] => Array
                (
                    [id] => 3
                    [value] => asdasd
                )

        )

)

您的JSON返回Null,因为在JSON中,密钥应为字符串。您的JSON格式不正确,因此返回Null。
尝试将其重写为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 {
 "id":"1",
 "fields":[
    {
     "id":"1",
     "value":"asdasd"

    },
    {
     "id":"2",
     "value":"asdasd"

    },{
     "id":"3",
     "value":"asdasd"
      }
    ]
}