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.)
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);
?>
Your JSON string is invalid: keys need to be quoted as well. Use JSONlint website, to check JSON validity.
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"
}]';
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