多个对象数组中的json_decode

时间:2013-08-30 14:29:34

标签: php arrays json

我有一个包含多个对象的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 个答案:

答案 0 :(得分:2)

您的JSON字符串无效:还需要引用密钥。使用JSONlint网站检查JSON有效性。

答案 1 :(得分: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"
}]';

答案 2 :(得分: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

答案 3 :(得分:0)

创建验证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);
?>