Back to results for “JSON Handling in PHP”
PHP › JSON Handling in PHP

How do you properly handle errors when parsing potentially invalid JSON, and how does the JSON_THROW_ON_ERROR flag simplify this compared to manually checking json_last_error?

Intermediate

Answer

By default, json_decode returns null if it encounters invalid JSON, but null is also a valid JSON value itself, making it ambiguous whether decoding actually failed or the JSON genuinely contained a null value, which historically required manually checking json_last_error afterward, while passing the JSON_THROW_ON_ERROR flag instead causes json_decode to throw a proper catchable JsonException on failure, letting you handle invalid JSON using a standard try catch block instead of manually checking an error code after every single call.
try {
    $data = json_decode($jsonString, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    echo 'Invalid JSON received: ' . $e->getMessage();
}
Real-world example An API integration script switches from manually checking json_last_error after every decode call to using the JSON_THROW_ON_ERROR flag, significantly simplifying its error handling code with a single consistent try catch block.

Common follow-ups: What specific error codes can json_last_error return besides indicating success?;Is JSON_THROW_ON_ERROR available in older PHP versions?