I tried to parse a JSON file using PHP. But I am stuck now.
This is the content of my JSON file:
{
"John": {
"status":"Wait"
},
"Jennifer": {
"status":"Active"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
And this is what I have tried so far:
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string, true);
echo $json_a['John'][status];
echo $json_a['Jennifer'][status];
But because I don't know the names (like 'John'
, 'Jennifer'
) and all available keys and values (like 'age'
, 'count'
) beforehand, I think I need to create some foreach loop.
I would appreciate an example for this.
It's completely beyond me that no one pointed out that your begining "tags" are wrong. You're creating an object with {}, while you could create an array with [].
With this change, the json will be parsed as an array instead of an object. And with that array, you can do whatever you want, like loops etc.
When you decode a json string, you will get an object. not an array. So the best way to see the structure you are getting, is to make a var_dump of the decode. (this var_dump can help you understand the structure, mainly in complex cases).
Try
You have to give like this:
Which gives the result :
Try:
Try This