json_decode($body, true) returns null and my code then crashes with 'Trying to access array offset on null'. How do I find out what is wrong with the JSON and handle it cleanly?
DEV3 Developer Forum
How do I detect and handle JSON errors in PHP (json_decode returns null)?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
dev3 ·
0
1 reply
dev3 · Accepted answer
json_decode returns null both for invalid JSON and for the valid JSON text null. Instead of checking the return value, use the exception flag (PHP 7.3+).
try {
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON: ' . $e->getMessage()]);
exit;
}
Messages include "Syntax error", "Malformed UTF-8 characters, possibly incorrectly encoded" and "Maximum stack depth exceeded". Without the flag:
$data = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_last_error_msg();
}
Frequent causes
- Single quotes or trailing commas: JSON requires double quotes and has no trailing commas or comments.
- UTF-8 BOM at the start of a file or API response: strip with
ltrim($body, "\xEF\xBB\xBF"). - Wrong encoding: data from a Latin-1 database must be converted (
mb_convert_encoding($s, 'UTF-8', 'ISO-8859-1')) beforejson_encode. A bad byte makesjson_encodereturnfalse. - PHP warnings or HTML printed before the JSON, making the body invalid.
- Reading a request body: use
file_get_contents('php://input')for JSON POST bodies.$_POSTis empty forapplication/json. - Large integers or floats: decode with
JSON_BIGINT_AS_STRING.
Encoding options
echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
Set the header Content-Type: application/json; charset=utf-8 before output.
Validate the shape
After decoding check that expected keys exist:
$email = $data['email'] ?? null;
if (!is_string($email)) { /* 422 */ }
Associative array vs object: the second argument true returns arrays; omit for stdClass objects.
Paste a payload into the JSON formatter to locate the exact syntax error.
0