Library contents

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

  1. Start with JSON text {"n":2}
  2. Do this Decode and read field n
  3. Result Number 2
Decoding turns the text representation into an object or record with a numeric field.

Syntax

PHP 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.

From the programdeclare(strict_types=1)
First output linenull
lesson.php
<?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";
    }
}
Output
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

Advertisements

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?

Given{"count":4}
Worked result4

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?

Given{"count":0}
Worked result0