2

我有一个包含多个对象的 JSON 数组,并试图用来json_decode制作一个关联数组。

样本数据

$json='[{   
         type: "cool",
         category: "power",
         name: "Robert Downey Jr.",
         character: "Tony Stark / Iron Man",
         bio: "cool kid"
     },
       {
         type: "cool",
         category: "power",
         name: "Chris Hemsworth",
         character: "Thor",
         bio: "cool kid"
     },
     {
         type: "NotCool",
         category: "nothing",
         name: "Alexis Denisof",
         character: "The Other",
         bio: "cool kid"
     }]';

这就是我正在做的事情:

$data = json_decode($json, true);

这给了我一个NULL结果。我究竟做错了什么?

(我是 PHP 新手。)

4

4 回答 4

2

您的 JSON 字符串无效:键也需要被引用。使用JSONlint网站,检查 JSON 的有效性。

于 2013-08-30T14:35:07.543 回答
1

创建验证 Json 试试这个

<?php
$json='[
    {
        "type": "cool",
        "category": "power",
        "name": "Robert Downey Jr.",
        "character": "Tony Stark / Iron Man",
        "bio": "cool kid"
    },
    {
        "type": "cool",
        "category": "power",
        "name": "Chris Hemsworth",
        "character": "Thor",
        "bio": "cool kid"
    },
    {
        "type": "NotCool",
        "category": "nothing",
        "name": "Alexis Denisof",
        "character": "The Other",
        "bio": "cool kid"
    }
]';
$data = json_decode($json, true);
echo "<pre>" ;
print_r($data);
?>
于 2013-08-30T14:37:24.293 回答
1

这不是有效的 JSON。对象中的键需要用双引号 ( ") 引用。

它应该是:

$json='[{
     "type": "cool",
     "category": "power",
     "name": "Robert Downey Jr.",
     "character": "Tony Stark / Iron Man",
     "bio": "cool kid"
},
{
     "type": "cool",
     "category": "power",
     "name": "Chris Hemsworth",
     "character": "Thor",
     "bio": "cool kid"
},
{
     "type": "NotCool",
     "category": "nothing",
     "name": "Alexis Denisof",
     "character": "The Other",
     "bio": "cool kid"
}]';
于 2013-08-30T14:35:16.040 回答
1

你需要在属性名称周围加上双引号,所以它应该是

JSON

[{   
    "type" : "cool",
    "category" : "power",
    "name" : "Robert Downey Jr.",
    "character" : "Tony Stark / Iron Man",
    "bio" : "cool kid"
}]

试试看嘛

PHP

echo json_encode(array("name" => "Tony Stark"));

你会看到有效的json

于 2013-08-30T14:36:07.890 回答