1.2.622. Json_encode() Without Catching Exceptions

json_encode() and json_decode() should use the exception system, to detect invalid JSON syntax.

The second argument is a bitmask, and shall include JSON_THROW_ON_ERROR, so that both function may emit an exception when a parsing error happen. That exception can then be caught with a try/catch structure. Alternatively, the error may be check by calling json_last_error() function. It will not be empty if an error is called.

<?php

try{
     echo json_encode($response,  JSON_THROW_ON_ERROR | JSON_PRETY_PRINT);
} catch (\JsonException $e) {
     echo "Sorry, an error occured.";
}
?>

See also json_encode().

1.2.622.1. Suggestions

  • Add the JSON_THROW_ON_ERROR in the second argument.

  • Call json_validate() on the data, before parsing it.

  • Check json_last_error() after the parsing, to detect any error

1.2.622.2. Specs

Short name

Structures/JsonEncodeExceptions

Rulesets

All, Changed Behavior, Suggestions

Exakat since

2.5.0

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

json, error-handling

Available in

Entreprise Edition, Exakat Cloud