json_validate() — Validate Without Decoding
PHP 8.3 added phpjson_validate — a function that checks if a string is valid JSON without actually decoding it. Before this, you had to call json_decode() and check json_last_error(), which meant allocating memory for a data structure you didn't need.
// Before: decode the entire payload just to check if it's valid
$data = json_decode($input);
if (json_last_error() !== JSON_ERROR_NONE) {
return 'Invalid JSON';
}
// After: validate without allocating a single array or object
if (!json_validate($input)) {
return 'Invalid JSON';
}
// With depth limit — protect against deeply nested payloads
if (!json_validate($input, depth: 32)) {
return 'JSON too deeply nested';
}
// Common pattern: validate first, decode only if valid
if (json_validate($payload)) {
$data = json_decode($payload, true, flags: JSON_THROW_ON_ERROR);
processData($data);
}
This is especially valuable for API gateways and middleware that need to validate JSON bodies before routing them — you skip the memory cost of decoding entirely.
Significance: Performance
Validation and parsing are different operations with different costs.
json_validate() recognizes this: when you only need a yes/no answer, you shouldn't pay the memory cost of building the decoded structure. It's the kind of targeted optimization that shows a maturing standard library.