PHP: Decode a JSON string into an array.

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:

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.

This means that we need to do the following to fix the fatal error above:

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.

Facebook Comments