Key points
json_decode()returnsnullon any error: useJSON_THROW_ON_ERRORto get an exception carrying the real cause.- The usual suspects: a trailing comma, single quotes, a BOM at the start of a file, and text that isn’t UTF-8.
- On the
json_encode()side,JSON_UNESCAPED_UNICODEandJSON_UNESCAPED_SLASHESkeep output readable, andarray_values()stops a list turning into an object.
An API call that “returns nothing”, a config file that’s ignored, a variable that’s null even though the file is clearly there: in PHP, most of these bugs come from a json_decode() that failed silently. In the other direction, json_encode() turns accented characters into u00e9, converts a list into an object or returns false with no explanation. We handle JSON on every project, from payment webhooks to catalogue imports. Here are the causes we actually run into, and how to write code that reports its errors instead of swallowing them.
Why json_decode returns null (and how to find the real cause)
By default, json_decode() raises no error at all: it returns null. The catch is that null is also the perfectly valid result of decoding the JSON null. So you can’t tell “the data is empty” from “the JSON is broken” without checking json_last_error(), which hardly anyone does.
<?php
$json = '{"name": "Coffee", "price": 3.5,}'; // trailing comma: invalid JSON
$data = json_decode($json, true);
var_dump($data); // NULL
echo json_last_error_msg(); // Syntax error
// Since PHP 7.3: an exception instead of a silent null
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
error_log('Invalid JSON: ' . $e->getMessage());
$data = null;
}
Since PHP 7.3, the JSON_THROW_ON_ERROR flag turns any error into a JsonException. It’s the setting we use everywhere: a format error shows up in the logs instead of travelling as null until it surfaces as an “Undefined array key” three files later. Note that with this flag, json_last_error() isn’t updated; read the exception message instead.
The messages are terse (“Syntax error”, “Malformed UTF-8 characters”), but they point you in the right direction straight away. The most common causes:
- a trailing comma after the last item, fine in JavaScript but forbidden in JSON;
- single quotes or unquoted keys, usually in hand-written JSON;
- a BOM (three invisible bytes) at the start of a file saved as “UTF-8 with BOM” by a Windows editor;
- text that isn’t UTF-8, typically an export from legacy software in Windows-1252 or ISO-8859-1;
- nesting deeper than the third argument allows (512 levels by default);
- a response that isn’t JSON at all: an HTML error page from the API, a PHP warning printed before the JSON, an empty body.
For files, we always clean up both encoding traps before decoding:
<?php
$raw = file_get_contents(__DIR__ . '/export.json');
// File saved as "UTF-8 with BOM": strip the 3 leading bytes
$raw = preg_replace('/^xEFxBBxBF/', '', $raw);
// File produced by legacy software in Windows-1252: convert it
if (!mb_check_encoding($raw, 'UTF-8')) {
$raw = mb_convert_encoding($raw, 'UTF-8', 'Windows-1252');
}
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
When the source is an API, log the raw response body when decoding fails, truncated if it’s long. The cause is usually obvious: an HTML maintenance page, a proxy error, JSON cut short by a timeout.
Associative array or object: the second argument
Without a second argument, json_decode() returns stdClass objects, so you write $data->name. Pass true and you get associative arrays: $data['name']. Both work; what matters is picking one convention per project. Mixing them is a classic source of “Cannot use object of type stdClass as array” errors.
We prefer associative arrays for data coming from outside, because they work naturally with isset(), the ?? operator and the array_* functions.
One detail that can hurt: very large integers, such as some IDs returned by APIs, exceed PHP’s integer range and are converted to floats, losing precision. The JSON_BIGINT_AS_STRING flag keeps them intact as strings.
json_encode: unicode, slashes, lists and numbers
By default, json_encode() escapes every non-ASCII character and every forward slash. The result is valid, but unreadable in a file or a log, and longer:
<?php
$product = ['name' => 'Crème brûlée', 'url' => 'https://example.com/desserts/creme', 'price' => 6.0];
echo json_encode($product);
// {"name":"Cru00e8me bru00fblu00e9e","url":"https://example.com/desserts/creme","price":6}
echo json_encode(
$product,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR
);
// {"name":"Crème brûlée","url":"https://example.com/desserts/creme","price":6.0}
(JSON_PRESERVE_ZERO_FRACTION keeps the .0 on whole floats, useful for strictly typed clients.) The most frequent trap involves lists. PHP has only one array type; json_encode() outputs a JSON list only when the keys are 0, 1, 2… in order. As soon as an array_filter() or an unset() leaves a gap, the array becomes an object, and the JavaScript calling data.tags.map() breaks:
<?php
echo json_encode([]); // []
echo json_encode(new stdClass()); // {}
echo json_encode(['a', 'b']); // ["a","b"]
echo json_encode([1 => 'a', 2 => 'b']); // {"1":"a","2":"b"}
$tags = array_filter(['php', '', 'json']); // keys 0 and 2: key 1 is gone
echo json_encode($tags); // {"0":"php","2":"json"}
echo json_encode(array_values($tags)); // ["php","json"]
The reverse happens too: an empty array is encoded as [] when the client expects an object {}. Use new stdClass() or (object) [] at that exact spot, rather than JSON_FORCE_OBJECT, which also turns every genuine list into an object.
Finally, json_encode() returns false if a string contains invalid UTF-8, which happens with old or imported data. With JSON_THROW_ON_ERROR, you’ll know at once. If you’d rather have degraded output than an error, JSON_INVALID_UTF8_SUBSTITUTE swaps invalid bytes for a replacement character, but fixing the encoding at the source is the real cure.
Receiving and returning JSON in a PHP API
When the browser sends JSON, $_POST stays empty: PHP only fills it for classic form submissions. You need to read the raw body from php://input. Here’s the skeleton we use for a simple endpoint without a framework:
<?php
// api/order.php: receives an order as JSON, replies with JSON (PHP 8.1+)
header('Content-Type: application/json; charset=utf-8');
function respond(int $status, array $body): never
{
http_response_code($status);
echo json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
exit;
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
respond(405, ['error' => 'Method not allowed']);
}
// $_POST stays empty when the body is JSON: read the raw input stream
$raw = file_get_contents('php://input');
try {
$input = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
} catch (JsonException) {
respond(400, ['error' => 'Invalid JSON']);
}
// Valid JSON isn't necessarily an object: "42" or "null" decode just fine
if (!is_array($input) || !isset($input['product_id'], $input['quantity'])) {
respond(422, ['error' => 'product_id and quantity are required']);
}
$quantity = filter_var($input['quantity'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($quantity === false) {
respond(422, ['error' => 'Invalid quantity']);
}
// … save the order …
respond(201, ['ok' => true]);
Three things make the difference in production. The Content-Type: application/json header is sent before any output, otherwise PHP complains that headers were already sent. Status codes are consistent (400 for unreadable JSON, 422 for invalid data), so the client can react properly. And valid JSON is never treated as trustworthy: check the type and every field, exactly as you would for a form.
In WordPress, use wp_send_json_success() and wp_send_json_error() in AJAX handlers and wp_json_encode() elsewhere: they send the right headers and handle common encoding problems. In a REST API route, simply return an array or a WP_REST_Response and let WordPress do the encoding.
FAQ
Why is my JSON valid in the browser but not in PHP?
Often because it isn’t JSON but a JavaScript object literal: single quotes, unquoted keys, a trailing comma. The browser accepts that in code, but neither JSON.parse() nor json_decode() will. Also check for a BOM or a PHP warning printed before the JSON.
Should I always use JSON_THROW_ON_ERROR?
On PHP 7.3 or later, yes: it’s the only reliable way to tell an error from JSON that genuinely is null. Wrap the call in try/catch wherever invalid data is to be expected, such as user input or a third-party API.
How do I print readable JSON for debugging?
Add JSON_PRETTY_PRINT to the json_encode() flags, along with JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES. Keep it for logs and files humans read; an API doesn’t need it.
API integrations, webhooks, data imports: we build robust JSON exchanges in PHP and WordPress that report their errors instead of hiding them.



