Decode JSON and catch bad input

JSON_THROW_ON_ERROR turns silent failures into exceptions you can catch.

PHP · Decode JSON and catch bad inputIntermediate
function readJson(string $raw): array
{
    try {
        $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
    } catch (JsonException $e) {
        throw new InvalidArgumentException('Invalid JSON: ' . $e->getMessage());
    }
    if (!is_array($data)) {
        throw new InvalidArgumentException('JSON must be an object or array');
    }
    return $data;
}

$body = readJson(file_get_contents('php://input') ?: '{}');
echo json_encode(['ok' => true, 'items' => count($body)], JSON_THROW_ON_ERROR);
jsonexceptionapi