This is a short tutorial on how to decode a JSON string into an associative array using PHP. To accomplish this, we will be using the inbuilt json_decode function, which has been available since PHP version 5.2.
“Cannot use object of type stdClass as array”
One pitfall of the json_decode function is that by default, it will convert a JSON string into an object. Take the following code example, which will throw a fatal error:
//Example JSON string. $jsonStr = '{"username":"mr_madman","last_activity":"2019-29-07 16:46:21"}'; //Decode the JSON string using json_decode $jsonDecoded = json_decode($jsonStr); //Print out the username. echo $jsonDecoded['username'];
If you run the code above, the following fatal error will be thrown:
Fatal error: Cannot use object of type stdClass as array
This is because json_decode decoded our JSON string into a stdClass object instead of an associative array. The error occurred when we subsequently attempted to reference the $jsonDecoded object as if it were an array.
How do I convert the JSON string into an array?
To decode a JSON string into an associative array, you will need to set the second parameter of json_decode to TRUE. The second parameter of json_decode is an optional parameter called $assoc. By default, this parameter is set to FALSE.
//Decode the JSON string into an array using json_decode $jsonDecoded = json_decode($jsonStr, true);
This means that we need to do the following to fix the fatal error above:
//Example JSON string. $jsonStr = '{"username":"mr_madman","last_activity":"2019-29-07 16:46:21"}'; //Decode the JSON string using json_decode $jsonDecoded = json_decode($jsonStr, true); //Print out the username. echo $jsonDecoded['username'];
If you take a close look at the example above, you will see that it is pretty much the same as the first code snippet. The only difference is that I passed a true boolean value in as the second parameter for json_decode.
And that’s it! Hopefully, you found this post to be helpful!
Read also: JSON error handling with PHP.