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
- 1Malformed JSON string passed to json_decode
- 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());
}Same error in other languages
Sources
Official documentation ↗
PHP Manual
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev