Why This Happens
json_decode() returns null when the input is not valid JSON. Common issues include using single quotes instead of double quotes, trailing commas after the last element, unescaped control characters, or a UTF-8 BOM at the start of the string. Always check json_last_error() after decoding.
The Problem
$json = "{'name': 'Alice'}"; // Single quotes are not valid JSON
$data = json_decode($json, true);
echo $data['name']; // Error: $data is nullThe Fix
$json = '{"name": "Alice"}';
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Invalid JSON: ' . json_last_error_msg());
}
echo $data['name'];Step-by-Step Fix
- 1
Check the raw JSON
Print the raw JSON string to see its actual content. Look for single quotes, trailing commas, unescaped characters, or BOM markers.
- 2
Validate with json_last_error
Call json_last_error() and json_last_error_msg() after json_decode() to get a specific error description.
- 3
Fix the JSON source
Correct the JSON syntax at its source. Use a JSON validator tool to find the exact location of the syntax error.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free