JSON Errors
A JSON error is a problem that stops JSON text from decoding into a value. PHP reports the problem, and a program can check the report or catch it as an exception.
Broken text gives null
The text {oops is not valid JSON. decode gives null, and json_last_error_msg prints the message for that failure.
<?php
$result = json_decode("{oops");
var_dump($result);
echo json_last_error_msg() . "\n";A flag turns the failure into an exception
A flag is an option constant passed as an argument. JSON_THROW_ON_ERROR makes the same decode throw, and the catch block prints the message.
<?php
try {
$result = json_decode("{oops", false, 512, JSON_THROW_ON_ERROR);
echo "Decoded\n";
} catch (JsonException $e) {
echo $e->getMessage() . "\n";
}Valid text with the flag decodes clean
The text here is valid JSON. The flag stays set, no exception is thrown, and the name prints.
<?php
try {
$data = json_decode('{"name":"Hana"}', true, 512, JSON_THROW_ON_ERROR);
echo $data["name"] . "\n";
echo "No error\n";
} catch (JsonException $e) {
echo $e->getMessage() . "\n";
}Example
<?php
$settings = ["theme" => "light"];
$text = "{oops";
try {
$settings = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
echo "Loaded\n";
} catch (JsonException $e) {
echo "Broken settings: " . $e->getMessage() . "\n";
}
echo "Theme: " . $settings["theme"] . "\n";Key points
- json_decode gives null when the JSON text is broken and no flag is set.
- Use json_last_error_msg to read the message for the last decode.
- JSON_THROW_ON_ERROR is a flag that makes decode throw an exception on bad text.
- The exception type for a JSON problem is JsonException.
- A catch block can print the message from a JsonException with getMessage.
In this example, the settings start as a fallback array with the light theme. The broken text fails to decode with the throw flag set, so the catch block prints its message. The last line prints the fallback theme, which stayed in place.
Note
The text null is valid JSON, so a null result alone does not prove an error.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which flag makes json_decode throw a JsonException on broken text?