Skip to content

24: Locate a JSON Syntax Error

Find the location of a syntax error in a multi-line JSON document. PHP 8.6 includes position information in the diagnostic message.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable json-error-location.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/24-json-error-location/json-error-location.php
json-error-location.php
<?php
declare(strict_types=1);
$document = "{\n \"items\": [1, 2,]\n}";
try {
json_decode($document, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
echo $error->getMessage(), PHP_EOL;
}
json_decode($document);
echo json_last_error_msg(), PHP_EOL;
Syntax error near location 2:18
Syntax error near location 2:18

Both the thrown JsonException and json_last_error_msg() can describe the location. Use the numeric error code for program logic because message wording can change. Read the last-error message immediately after the applicable call without JSON_THROW_ON_ERROR.

Move the trailing comma to another line and inspect the new diagnostic. Remove it and confirm decoding succeeds.

Continue with Show Function Arguments in PHP Errors.