Reputation: 427
I have a JSON array with multiple objects and trying to use json_decode
to make an associate array.
Sample data
$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"
}]';
Here's what I am doing:
$data = json_decode($json, true);
which gives me a NULL
result. What am I doing wrong?
(I'm new to PHP.)
Upvotes: 2
Views: 3727
Reputation: 62387
Your JSON string is invalid: keys need to be quoted as well. Use JSONlint website, to check JSON validity.
Upvotes: 2
Reputation: 4620
Create Validate Json Try this
<?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);
?>
Upvotes: 1
Reputation: 6230
you need double quotes around property names so it should be
JSON
[{
"type" : "cool",
"category" : "power",
"name" : "Robert Downey Jr.",
"character" : "Tony Stark / Iron Man",
"bio" : "cool kid"
}]
just try
PHP
echo json_encode(array("name" => "Tony Stark"));
and you will see valid json
Upvotes: 1
Reputation: 227240
This isn't valid JSON. The keys in the objects need to be quoted, with double quotes ("
).
It should be:
$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"
}]';
Upvotes: 1