Home/Guides/PHP json_decode Examples

PHP JSON Guides

PHP json_decode Examples

Practical json_decode examples for associative arrays, error handling, and common JSON mistakes.

PHP json_decode() converts a JSON string into an object or associative array.

Code examples

$data = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException(json_last_error_msg());
}

Use exceptions in newer code:

$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);

Common errors

JSON does not allow trailing commas, comments, or unquoted keys. PHP also expects valid UTF-8.

Try the PHP JSON Formatter Online.

FAQ

How do I get an array from json_decode?

Pass true as the second argument: json_decode($json, true).

How do I debug invalid JSON in PHP?

Check json_last_error_msg after decoding.

Related tools