json_decode() returns null
Syntax error
Where JSON.parse stops
{
'name': 'Ada',
'active': true,What it means
json_decode does not throw by default. It returns null and expects you to ask what happened. null is also the correct result for the input null, so the return value on its own genuinely cannot tell you whether anything went wrong: json_last_error() is the only way to know.
It opens with the error marked. Nothing is uploaded. Find where the error is.
- Usually
- A genuine syntax errorThe input was not UTF-8Nesting deeper than the limitIt really was null
- Fix
- Pass the flag and let it throw:
json_decode($s, true, 512, JSON_THROW_ON_ERROR)raisesJsonExceptionon PHP 7.3 and later, which is almost always what you wanted.
The fix
Pass the flag and let it throw: json_decode($s, true, 512, JSON_THROW_ON_ERROR) raises JsonException on PHP 7.3 and later, which is almost always what you wanted. Without it, check json_last_error() !== JSON_ERROR_NONE and print json_last_error_msg().
{
'name': 'Ada',
'active': true,
}Lines 2 and 3 change.
{
"name": "Ada",
"active": true
}How the message appears
PHP does not throw by default, so these strings come from json_last_error_msg() rather than from an exception: or from JsonException if you passed JSON_THROW_ON_ERROR.
- Syntax error
- Malformed UTF-8 characters, possibly incorrectly encoded
- Control character error, possibly incorrectly encoded
- Maximum stack depth exceeded
What causes it
A genuine syntax error
json_last_error_msg()returnsSyntax error, which is all PHP will tell you: there is no position, no line and no column. Paste the document into the validator to find out where it is.The input was not UTF-8
JSON_ERROR_UTF8, reported as "Malformed UTF-8 characters". Latin-1 text from an older database or a file read with the wrong encoding. Convert first:mb_convert_encoding($s, "UTF-8", "ISO-8859-1").Nesting deeper than the limit
JSON_ERROR_DEPTH. The third argument defaults to512levels. Deeply nested documents need it raised explicitly.It really was null
The document contained the literal
null, decoding succeeded, and the result is correctlynull.if ($data === null)treats this valid document as a failure, which is a bug that only shows up on the one input nobody tests.
Worth knowing
Watch outLarge integers lose precision by default because they become floats. JSON_BIGINT_AS_STRING keeps them intact: relevant for IDs from APIs that use 64-bit numbers.
NoteThe second argument matters: json_decode($s, true) gives associative arrays, and without it you get stdClass objects. It changes nothing about whether the document is valid, only the shape you get back.
NoteThe encoding direction has the same silence: json_encode returns false rather than throwing, and also needs JSON_THROW_ON_ERROR to be useful.