Since PHP 8.6, the error message returned by the json_last_error_msg function and the message of the JsonException class include the location of the error. The location is added at the end of the message in the line:column format. Before PHP 8.6, the message stated only that a syntax error occurred, without saying where.
The following code decodes an invalid JSON document and prints the error message:
<?php
$json = '{
"name": "John",
"age" 30
}';
json_decode($json);
echo json_last_error_msg();
Before PHP 8.6:
Syntax error
Since PHP 8.6:
Syntax error near location 3:9
On line 3 the 30 starts at column 9, counting the two spaces of indentation. It is the token after the missing colon.
The JsonException class is thrown when the JSON_THROW_ON_ERROR flag is passed:
<?php
$json = '{
"name": "John",
"age" 30
}';
try {
json_decode($json, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo $e->getMessage(); // Syntax error near location 3:9
}
Only syntax errors include the location. Other JSON errors are not changed. For example, json_encode(['a' => NAN]) still fails with the Inf and NaN cannot be JSON encoded message.
Leave a Comment
Cancel reply