How can I parse a JSON file with PHP? [duplicate]

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.

10

16 Answers

To iterate over a multidimensional array, you can use RecursiveArrayIterator

$jsonIterator = new RecursiveIteratorIterator( new RecursiveArrayIterator(json_decode($json, TRUE)), RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) { if(is_array($val)) { echo "$key:\n"; } else { echo "$key => $val\n"; }
}

Output:

John:
status => Wait
Jennifer:
status => Active
James:
status => Active
age => 56
count => 10
progress => 0.0029857
bad => 0

run on codepad

7

I can't believe so many people are posting answers without reading the JSON properly.

If you foreach iterate $json_a alone, you have an object of objects. Even if you pass in true as the second parameter, you have a two-dimensional array. If you're looping through the first dimension you can't just echo the second dimension like that. So this is wrong:

foreach ($json_a as $k => $v) { echo $k, ' : ', $v;
}

To echo the statuses of each person, try this:

<?php
$string = file_get_contents("/home/michael/test.json");
if ($string === false) { // deal with error...
}
$json_a = json_decode($string, true);
if ($json_a === null) { // deal with error...
}
foreach ($json_a as $person_name => $person_a) { echo $person_a['status'];
}
?>
4

The most elegant solution:

$shipments = json_decode(file_get_contents("shipments.js"), true);
print_r($shipments);

Remember that the json-file has to be encoded in UTF-8 without BOM. If the file has BOM, then json_decode will return NULL.

Alternatively:

$shipments = json_encode(json_decode(file_get_contents("shipments.js"), true));
echo $shipments;
4

Try

<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){ echo $key . ':' . $value;
}
?>
3

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 [].

[ // <-- Note that I changed this { "name" : "john", // And moved the name here. "status":"Wait" }, { "name" : "Jennifer", "status":"Active" }, { "name" : "James", "status":"Active", "age":56, "count":10, "progress":0.0029857, "bad":0 }
] // <-- And this.

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.

5

Try This

 $json_data = '{ "John": { "status":"Wait" }, "Jennifer": { "status":"Active" }, "James": { "status":"Active", "age":56, "count":10, "progress":0.0029857, "bad":0 } }'; $decode_data = json_decode($json_data); foreach($decode_data as $key=>$value){ print_r($value); }
2

Try:

$string = file_get_contents("/home/michael/test.json");
$json = json_decode($string, true);
foreach ($json as $key => $value) { if (!is_array($value)) { echo $key . '=>' . $value . '<br />'; } else { foreach ($value as $key => $val) { echo $key . '=>' . $val . '<br />'; } }
}
1

More standard answer:

$jsondata = file_get_contents(PATH_TO_JSON_FILE."/jsonfile.json");
$array = json_decode($jsondata,true);
foreach($array as $k=>$val): echo '<b>Name: '.$k.'</b></br>'; $keys = array_keys($val); foreach($keys as $key): echo '&nbsp;'.ucfirst($key).' = '.$val[$key].'</br>'; endforeach;
endforeach;

And the output is:

Name: John Status = Wait
Name: Jennifer Status = Active
Name: James Status = Active Age = 56 Count = 10 Progress = 0.0029857 Bad = 0
3

Loop through the JSON with a foreach loop as key-value pairs. Do type-checking to determine if more looping needs to be done.

foreach($json_a as $key => $value) { echo $key; if (gettype($value) == "object") { foreach ($value as $key => $value) { # and so on } }
}
1
<?php
$json = '{ "response": { "data": [{"identifier": "Be Soft Drinker, Inc.", "entityName": "BusinessPartner"}], "status": 0, "totalRows": 83, "startRow": 0, "endRow": 82 }
}';
$json = json_decode($json, true);
//echo '<pre>'; print_r($json); exit;
echo $json['response']['data'][0]['identifier'];
$json['response']['data'][0]['entityName']
echo $json['response']['status'];
echo $json['response']['totalRows'];
echo $json['response']['startRow'];
echo $json['response']['endRow'];
?>
2

Try it:

foreach ($json_a as $key => $value) { echo $key, ' : '; foreach($value as $v) { echo $v." "; }
}
1

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).

<?php $json = file_get_contents('/home/michael/test.json'); $json_a = json_decode($json); var_dump($json_a); // just to see the structure. It will help you for future cases echo "\n"; foreach($json_a as $row){ echo $row->status; echo "\n"; }
?>
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);
foreach($json_a as $person => $value)
{ foreach($value as $key => $personal) { echo $person. " with ".$key . " is ".$personal; echo "<br>"; }
}
1

The quickest way to echo all json values is using loop in loop, the first loop is going to get all the objects and the second one the values...

foreach($data as $object) { foreach($object as $value) { echo $value; } }

You have to give like this:

echo $json_a['John']['status'];
echo "<>"
echo $json_a['Jennifer']['status'];
br inside <>

Which gives the result :

wait
active
2

I am using below code for converting json to array in PHP, If JSON is valid then json_decode() works well, and will return an array, But in case of malformed JSON It will return NULL,

<?php
function jsonDecode1($json){ $arr = json_decode($json, true); return $arr;
}
// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );
?>

If in case of malformed JSON, you are expecting only array, then you can use this function,

<?php
function jsonDecode2($json){ $arr = (array) json_decode($json, true); return $arr;
}
// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );
?>

If in case of malformed JSON, you want to stop code execution, then you can use this function,

<?php
function jsonDecode3($json){ $arr = (array) json_decode($json, true); if(empty(json_last_error())){ return $arr; } else{ throw new ErrorException( json_last_error_msg() ); }
}
// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );
?>
4

You Might Also Like