PHP / Editorial solution guide

Diagnose JSON decoding errors and null results

Distinguish invalid JSON from valid absence and domain errors.

About 2 min readContent reviewed

Read-only knowledge base · No public comments

Recognize the symptoms

A decoded value is null or a JSON request is rejected unexpectedly.

Understand the likely causes

  • Malformed input, invalid UTF-8, depth limits, or a valid JSON null can produce different outcomes.

Capture the failure

Capture the first JSON error and the boundary that supplied the bytes, using a small synthetic payload. Record the configured size and nesting limits and whether the failure occurred during decoding or encoding. A valid JSON null is not the same as malformed JSON, and a valid JSON value can still have the wrong application shape. Avoid logging private payloads while reproducing the problem.

Inspect input and flags

json_decode expects UTF-8 input. Syntax errors, invalid encoding, and excessive nesting require different investigation, so preserve the error category rather than assuming an empty object. Without an explicit error policy, a null result can be ambiguous because JSON null is valid. Check the configured flags and distinguish a decoding failure from a successfully decoded value that later fails schema or domain validation.

If encoding fails on output, inspect the value and UTF-8 contract separately from the incoming decode path; the two operations can fail for different reasons.

Handle decode errors

Use JSON_THROW_ON_ERROR when exceptions fit the application’s error contract, and catch JsonException at a boundary that can report an invalid payload. The example decodes malformed synthetic text and prints a controlled message. Enforce input-size and nesting limits separately. After decoding, validate the expected object or array shape and each field before using the data or modifying state.

php Handle malformed JSON
<?php
declare(strict_types=1);

try {
    json_decode('{broken', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
    echo "invalid JSON\n";
}
Expected output
invalid JSON

The exception distinguishes malformed input from a valid JSON null.

Verify JSON cases

Test valid object input, valid null, malformed syntax, invalid UTF-8, and an excessive nesting case under the configured limit. Verify that each rejected payload produces the documented response and cannot update state. Repeat the original request using the same runtime configuration and flags. A successful parse of one sample does not establish that encoding, size limits, and domain validation are correct for all inputs.

Verify the fix

Valid null and invalid input follow distinct documented paths, and rejected input does not change state.

Keep it from recurring

  • Set explicit decoding flags and test syntax, encoding, depth, and domain shape.

Official references