1.2.128. Check JSON

Check errors whenever JSON is encoded or decoded.

In particular, NULL is a valid decoded JSON response. If you want to avoid mistaking NULL for an error, it is recommended to call json_last_error.

<?php

$encoded = json_encode($incoming);
// Unless JSON must contains some non-null data, this mistakes NULL and error
if(json_last_error() != JSON_ERROR_NONE) {
    die('Error when encoding JSON');
}

$decoded = json_decode($incoming);
// Unless JSON must contains some non-null data, this mistakes NULL and error
if($decoded === null) {
    die('ERROR');
}

?>

See also Option to make json_encode and json_decode throw exceptions on errors and json_last_error.

1.2.128.1. Suggestions

  • Always check after JSON operation : encoding or decoding.

  • Add a call to json_last_error()

  • Configure operations to throw an exception upon error (JSON_THROW_ON_ERROR), and catch it.

1.2.128.2. Specs

Short name

Structures/CheckJson

Rulesets

All, Analyze, CE, CI-checks

Exakat since

1.3.0

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

json

Examples

Woocommerce

Available in

Entreprise Edition, Community Edition, Exakat Cloud