json_decode Returns Null

json_decode() returns null with json_last_error(): JSON_ERROR_SYNTAX

Quick Answer

The JSON string you are trying to decode is malformed. Validate the JSON syntax, check for BOM characters, trailing commas, or single quotes instead of double quotes.

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 null

The 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. 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. 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. 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