PHP json_decode and JSON_THROW_ON_ERROR
json_decode with JSON_THROW_ON_ERROR raises JsonException on invalid JSON. The valid JSON literal null still decodes to PHP null.
A simple example
json_decode and JSON_THROW_ON_ERROR
- Start with JSON text {"n":2}
- Do this Decode and read field n
- Result Number 2
Syntax
$value = json_decode($text, true, 512, JSON_THROW_ON_ERROR)
Run this example in PHP
Save the program as lesson.php. Use PHP 8.2 or later.
php lesson.php
Separate JSON syntax errors from null
A batch processor must distinguish an anticipated input problem from a different failure. Examine the operation's error information before deciding whether to skip one record, report the cause or stop.
<?php
declare(strict_types=1);
foreach (['null', '{"qty":0}', '{"qty":}'] as $text) {
try {
$value = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
echo ($value === null ? 'null' : (string) $value['qty']) . "\n";
} catch (JsonException $error) {
echo "invalid JSON\n";
}
}
null 0 invalid JSON
A plain null result can be ambiguous without the exception flag. The example handles a valid null, an object containing zero, and a malformed document separately.
PHP documentation for json_decode and JSON_THROW_ON_ERROR
Read a locker report
A locker controller sends the number of free doors as JSON. Decode the JSON record before reading its count field. Which numeric count reaches the desk?
Record an empty tray
A sorter sends an explicit count of zero for an empty tray. Decode the JSON record before reading its count field. Which numeric count reaches the desk?