1.2.130. 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.130.1. Connex PHP features¶
1.2.130.1.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.130.1.2. Specs¶
Short name |
Structures/CheckJson |
Rulesets |
|
Exakat since |
1.3.0 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Examples |
|
Available in |