PHP 8.6: JSON: json_decode error/exception message now indicates the location of the error
In PHP 8.6, the json_decode and json_last_error_msg functions return the line and the position of the error. Prior to PHP 8.6, the error messages contained the type of the error and a description, but not exactly where the error occurred when it was parsed.
Starting with PHP 8.6, all JSON decoding failures attempt to include the location in the JSON string where the error occurred.
$json = '[{';
json_decode($json); // null
json_last_error_msg();
// "Syntax error near location 1:3"
Prior to PHP 8.6, json_last_error_msg() only returns Syntax error when the same string fails to decode.
When exceptions are enabled for the json_decode function using the JSON_THROW_ON_ERROR flag, the thrown JsonException exception message contains the location of the error:
$json = '[{';
json_decode($json, flags: JSON_THROW_ON_ERROR);
JsonException: Syntax error near location 1:3
$json = '[{';
try {
json_decode($json, flags: JSON_THROW_ON_ERROR);
}
catch (\JsonException $ex) {
echo $ex->getMessage(); // "Syntax error near location 1:3"
}
Additional examples
json_decode("{\n\t \"key1\": \"val1\",\n \t\"key2\": \"val2\n}");
json_last_error_msg(); // "Control character error, possibly incorrectly encoded near location 3:12"
json_decode('{"numbers": [1, 2, 3], "strings": ["a", "b", "c"], "booleans": [true, false, true}');
json_last_error_msg(); // "State mismatch (invalid or malformed JSON) near location 1:82"
json_decode('[[[[[[[[[[42]]]]]]]]]]', depth: 6);
json_last_error_msg(); // "Maximum stack depth exceeded near location 1:6"
json_decode("\"a\xb0b\"");
json_last_error_msg(); // "Malformed UTF-8 characters, possibly incorrectly encoded near location 1:1"
Backward Compatibility Impact
The location reporting from the JSON error handling is new in PHP 8.6. Because PHP does not expose lower-level JSON parsing, it is not possible to port this functionality to older PHP versions.
The json_last_error function continues to report the identical error codes across all PHP versions, ensuring compatibility with error code-based assertions.