json_decode
Parses a JSON string.
Syntax
json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixedParameters
| Parameter | Type | Description |
|---|---|---|
| $json | string | A string in JSON format. |
| $associative | ?bool | Optional. `true` returns arrays instead of objects. |
| $depth | int | Optional. The maximum nesting depth. |
| $flags | int | Optional. `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 25An invalid string:
<?php
try {
json_decode('not json', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
echo 'Invalid JSON';
}Output:
Invalid JSONNotes
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
- json_encode — Converts a value to a JSON string.
- file_get_contents — Reads a whole file into a string.
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.