JSON Errors / PHP
PHP json_decode returns NULLHow to Fix: PHP json_decode returns NULL
Unlike most languages, PHP's json_decode() does not throw on invalid JSON - it just returns null. Since null is also the correct result for decoding the valid document "null", errors slip through silently until something downstream breaks.
The actual error is waiting in json_last_error() / json_last_error_msg(), and since PHP 7.3 you can make json_decode throw a proper JsonException with the JSON_THROW_ON_ERROR flag - which is what modern code should do.
Common causes
1. Invalid JSON syntax
Single quotes, trailing commas, unquoted keys - json_last_error_msg() reports "Syntax error" for all of them.
json_decode("{'name': 'Ada'}") // NULL, JSON_ERROR_SYNTAX2. Malformed UTF-8 in the input
JSON must be UTF-8; data from Latin-1 databases or files produces "Malformed UTF-8 characters, possibly incorrectly encoded" (JSON_ERROR_UTF8).
3. Exceeded nesting depth
Documents nested deeper than the depth parameter (default 512) fail with JSON_ERROR_DEPTH - seen with pathological or machine-generated payloads.
4. Magic quotes / double escaping upstream
Input that was addslashes()-ed or escaped twice contains \" sequences that break parsing - inspect the raw string before decoding.
How to fix it
<?php
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
// e.g. "Syntax error" / "Malformed UTF-8 characters"
error_log("JSON decode failed: " . $e->getMessage());
throw $e;
}<?php
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("JSON error: " . json_last_error_msg());
error_log("First 200 chars: " . substr($json, 0, 200));
}<?php
// If the source is Latin-1/Windows-1252:
$utf8 = mb_convert_encoding($raw, 'UTF-8', 'ISO-8859-1');
$data = json_decode($utf8, true, 512, JSON_THROW_ON_ERROR);Frequently asked questions
How do I distinguish "invalid JSON" from a legitimate null value?
Either use JSON_THROW_ON_ERROR (invalid input throws, valid "null" returns null cleanly), or check json_last_error() === JSON_ERROR_NONE after decoding. Never infer failure from the null return value alone.
Why does my JSON work in JavaScript but return NULL in PHP?
Usually encoding: PHP strictly requires valid UTF-8 while browsers are forgiving. Check json_last_error_msg() for "Malformed UTF-8" and re-encode the source data. Depth limits and very large integers can also differ between environments.
Should I pass true as the second argument?
json_decode($json, true) returns associative arrays; without it you get stdClass objects. Arrays are the common choice for data manipulation; objects can be marginally cheaper and are needed if downstream code expects ->property access. Pick one convention per codebase.
Last updated:
Related JSON errors
You might also need
Free and in-browser, like everything on JSON Console. Browse all tools →