JsonException
PHPERRORCommonParsing

JSON encode or decode failed

Quick Answer

Always pass JSON_THROW_ON_ERROR to json_encode/json_decode so failures throw JsonException instead of silently returning null/false.

What this means

Thrown by json_encode() / json_decode() when the JSON_THROW_ON_ERROR flag is passed and the operation fails.

Why it happens
  1. 1Malformed JSON string passed to json_decode
  2. 2Non-UTF-8 string passed to json_encode

Fix

Use JSON_THROW_ON_ERROR

Use JSON_THROW_ON_ERROR
try {
    $data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
    throw new \InvalidArgumentException("Invalid JSON: " . $e->getMessage(), 0, $e);
}

Why this works

JSON_THROW_ON_ERROR makes failures catchable instead of silently returning null.

Code examples
Encode with flagphp
$json = json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
Old way to checkphp
// Without flag — check json_last_error()
$data = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new \RuntimeException(json_last_error_msg());
}

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All PHP errors