ERROR php data_parsing ai_generated true

json_decode(): Argument #1 ($json) must be of type string, null given / JSON_ERROR_SYNTAX: Syntax error

ID: php/json-decode-error

Also available as: JSON · Markdown
89%Fix Rate
90%Confidence
70Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
83 active

Root Cause

json_decode() errors in PHP 8.x occur when the input string is not valid JSON, is null, or contains malformed UTF-8 characters. In PHP 8.3, passing null to json_decode triggers a deprecation warning. Common sources include API responses with HTML error pages, BOM characters, or truncated response bodies.

generic

Workarounds

  1. 91% success Use JSON_THROW_ON_ERROR flag and validate input before decoding
    Pass the JSON_THROW_ON_ERROR flag to json_decode: 'json_decode($string, true, 512, JSON_THROW_ON_ERROR)'. This throws a JsonException on invalid input. Wrap in try-catch to handle gracefully. Before decoding, check that the input is a non-empty string.
  2. 86% success Strip BOM and validate UTF-8 encoding before json_decode
    Remove UTF-8 BOM with: '$json = preg_replace("/^\xEF\xBB\xBF/", "", $json);'. Validate UTF-8 encoding with mb_check_encoding($json, 'UTF-8'). If the source is an HTTP response, check the Content-Type header to ensure it is application/json and not an HTML error page.

Dead Ends

Common approaches that don't work:

  1. Wrapping json_decode in a try-catch without checking json_last_error() 82% fail

    json_decode() does not throw exceptions by default (unless JSON_THROW_ON_ERROR flag is used). It returns null on failure, so a try-catch without the flag will not catch anything. The error must be checked with json_last_error().

  2. Using regex to fix malformed JSON before decoding 73% fail

    Attempting to repair JSON with regex is fragile and error-prone. JSON has nested structures, escaped characters, and Unicode that regex cannot reliably parse. The real fix is to ensure the source produces valid JSON.

Error Chain

Leads to:
Preceded by:
Frequently confused with: