Wikis & learning

Read JSON and handle invalid input

JSON separates an interchange format from the PHP arrays you use inside your program. Decide how you want malformed input to behave.

JSON separates an interchange format from the PHP arrays you use inside your program. Decide how you want malformed input to behave.

How it works

Request associative arrays and enable exceptions. Treat a valid JSON value and a valid application record as two separate checks.

PHP example

<?php
$record = json_decode('{"name":"Calendar","enabled":true}', true, 512, JSON_THROW_ON_ERROR);
if (is_array($record) && isset($record['name'])) {
    echo $record['name'];
}

Expected result

Calendar

Try a variation

Remove the closing brace in the JSON string. Catch JsonException to report the syntax error.