Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

json_decode

Parses a JSON string.

Syntax

json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed

Parameters

ParameterTypeDescription
$jsonstringA string in JSON format.
$associative?boolOptional. `true` returns arrays instead of objects.
$depthintOptional. The maximum nesting depth.
$flagsintOptional. `JSON_THROW_ON_ERROR` throws an exception on failure.

Return value

mixedAn array, an object or a simple value; `null` on failure.

Examples

JSON to an array:

<?php
 
$user = json_decode('{"name": "Anna", "age": 25}', true);
 
echo $user['name'], ' ', $user['age'];

Output:

Anna 25

An invalid string:

<?php
 
try {
    json_decode('not json', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
    echo 'Invalid JSON';
}

Output:

Invalid JSON

Notes

Without true as the second argument JSON objects become PHP objects: $user->name instead of $user['name']. Without JSON_THROW_ON_ERROR a failure is indistinguishable from a valid null.

See also

Related recipes

In the tutorial

  • The JSON format — JSON in PHP — json_encode and json_decode, non-ASCII text, error handling and storing data in a file.

Thanks for reading!

Donate to the site — we work hard for you.