json_decode

json_decode($json, $associative, $depth, $flags)

Converts a string in JSON format into a PHP value. By default it returns JSON objects as stdClass objects, with the second parameter true as associative arrays. It is the opposite of json_encode().

Parameters

  • $json – a string in JSON format in UTF-8 encoding.
  • $associative – optional, true = objects are converted to associative arrays. The default is false (stdClass objects).
  • $depth – optional, the maximum nesting depth (default 512).
  • $flags – optional, for example JSON_THROW_ON_ERROR (as of PHP 7.3) or JSON_BIGINT_AS_STRING.

Examples

$json = '{"name":"Garth","languages":["PHP","MySQL"],"age":null}';
// as an object
$data = json_decode($json);
echo $data->name; // Garth
echo $data->languages[1]; // MySQL
// as an associative array
$data = json_decode($json, true);
echo $data["name"]; // Garth
echo count($data["languages"]); // 2
var_dump($data["age"]); // NULL
// invalid JSON – keys and strings must be in double quotes
var_dump(json_decode("{name: 'Garth'}")); // NULL
echo json_last_error_msg(); // Syntax error
// an error as an exception (as of PHP 7.3)
try {
  $data = json_decode("{error", true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
  echo "Invalid JSON: " . $e->getMessage(); // Invalid JSON: Syntax error
}
// data sent from JavaScript (fetch with a JSON body)
$input = json_decode(file_get_contents("php://input"), true);

Things to watch out for

  • A return value of null can mean an error, but also the valid JSON “null”. You can reliably detect an error with json_last_error() or the JSON_THROW_ON_ERROR flag.
  • JSON is stricter than JavaScript: keys and strings must be in double quotes and there must be no comma after the last element.
  • Integers larger than PHP_INT_MAX are converted to float and lose precision. If you need them exact, use the JSON_BIGINT_AS_STRING flag.
  • Data from JSON is user input just like $_POST – check that the required keys exist and that the values have the right type.

Related functions:
json_encode()
array_key_exists()
is_string()
serialize()
json_last_error()
json_validate()
simplexml_load_string()