json_decode returns null for both invalid input and valid JSON null — distinguishing failure in PHP 8.1+
0 reputation · 01 Jan 2023, 03:47 UTC
0 reputation · 01 Jan 2023, 03:47 UTC
Reliably detect whether json_decode() failed due to malformed input versus successfully decoding a JSON document whose top-level value is null.
The function returns PHP null in both cases, so the return value alone cannot signal failure. The standard approach is to call json_last_error() immediately after decoding and compare the result against JSON_ERROR_NONE. However, any subsequent JSON function call overwrites the error state, so the check must be atomic with the decode. In PHP 8.1 and later, passing null as the JSON string argument emits a deprecation notice because internal parameters are now non-nullable, which adds a version-dependent code path to consider when the input itself may be null.
json_last_error() is inspected before any other JSON operation can clobber it?null, and if so, what is the recommended guard that does not mask genuine decode failures?35775 reputation · 01 Jan 2023, 04:08 UTC
To reliably distinguish between a decoding failure and a successful decode of a JSON null value, you must guard against null inputs to avoid PHP 8.1+ deprecation notices, call json_decode(), and immediately capture the result of json_last_error() before any other JSON-related function is executed.
// 1. Guard against PHP 8.1+ deprecation notice for null arguments
if ($input === null) {
$decoded = null;
$isValid = false; // Or true, depending on your business logic for null input
} else {
$decoded = json_decode($input, true);
// 2. Atomic error check immediately following the decode
$isValid = (json_last_error() === JSON_ERROR_NONE);
}
The ambiguity arises because json_decode() returns the PHP value null in two distinct scenarios: when the input string is the valid JSON literal "null" and when the input is malformed. Because the return value is identical, the internal error state is the only source of truth.
json_last_error() is global to the process and is overwritten by any subsequent call to json_decode() or json_encode().null as the first argument to json_decode() now triggers a deprecation notice because internal functions are moving toward stricter type enforcement for non-nullable parameters."null" is valid JSON and will result in JSON_ERROR_NONE.This pattern assumes the environment is running PHP 8.1 or later. If the input variable is sourced from an external API or database, it is assumed that a PHP null (absence of value) should be handled differently than a JSON "null" (explicit null value).
Verification Steps:
'null': Verify $decoded is null and $isValid is true.'invalid-json': Verify $decoded is null and $isValid is false.null: Verify no deprecation notice is emitted and the guard handles the state.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.