Validating JSON with json_validate
suggest changeSometimes you only need to know whether a string is valid JSON. You don't need the data in it. Before PHP 8.3 the usual way to check was to call json_decode() and then look at json_last_error(). That builds the whole PHP array or object only to throw it away.
PHP 8.3 added json_validate():
json_validate(string $json, int $depth = 512, int $flags = 0): bool
It runs the same parser as json_decode() but doesn't build any PHP values. It returns true or false and sets the error that json_last_error() reports.
This article covers:
- what
json_validate()accepts and rejects - getting the reason for a failure with
json_last_error_msg() - how it compares with
json_decode()in memory and speed - the
$depthand$flagsparameters - when to skip it and decode directly with
JSON_THROW_ON_ERROR - a polyfill for older PHP versions
All examples need PHP 8.3 or newer. They were run with PHP 8.5.
Related topics: Decoding a JSON string and Debugging JSON errors.
Basic usage
Any JSON value counts as a valid document, including a bare string, number or null. Anything outside the JSON grammar fails: trailing commas, single quotes, unquoted keys, truncated input and the empty string.
<?php
$inputs = [
'{"name": "Ann", "age": 30}',
'[1, 2, 3]',
'"just a string"',
'42',
'null',
'{"name": "Ann",}', // trailing comma
"{'name': 'Ann'}", // single quotes
'{name: "Ann"}', // unquoted key
'[1, 2', // truncated
'', // empty string
];
foreach ($inputs as $input) {
printf("%-28s %s\n", var_export($input, true), json_validate($input) ? 'valid' : 'invalid');
}
Output:
'{"name": "Ann", "age": 30}' valid
'[1, 2, 3]' valid
'"just a string"' valid
'42' valid
'null' valid
'{"name": "Ann",}' invalid
'{\'name\': \'Ann\'}' invalid
'{name: "Ann"}' invalid
'[1, 2' invalid
'' invalid
Whitespace around the value is allowed, so " [1] \n" is valid.
The return value is a plain bool, which fixes an old problem with json_decode(): it returns null both for the valid document null and for an error.
<?php
var_dump(json_validate('null')); // valid JSON
var_dump(json_decode('null')); // decodes to null...
var_dump(json_decode('nul')); // ...and so does an error
var_dump(json_last_error_msg());
Output:
bool(true)
NULL
NULL
string(12) "Syntax error"
Finding out why validation failed
json_validate() sets the same error state as json_decode() and json_encode(). After a false result, call json_last_error() for the error code and json_last_error_msg() for a readable message:
<?php
function describeJsonError(string $json): string
{
if (json_validate($json)) {
return 'OK';
}
return sprintf('error %d: %s', json_last_error(), json_last_error_msg());
}
echo describeJsonError('{"id": 1}'), "\n";
echo describeJsonError('{"id": 1'), "\n";
echo describeJsonError("\"caf\xE9\""), "\n"; // Latin-1 byte, not UTF-8
echo describeJsonError('[[["deep"]]]'), "\n";
Output:
OK
error 4: Syntax error
error 5: Malformed UTF-8 characters, possibly incorrectly encoded
OK
The codes are the JSON_ERROR_* constants: 4 is JSON_ERROR_SYNTAX and 5 is JSON_ERROR_UTF8. The full table is in Debugging JSON errors. The message doesn't say where in the input the error is.
The error state is global and every JSON call overwrites it, so read it right after the call that failed. Calls that pass JSON_THROW_ON_ERROR are the exception. They don't touch it:
<?php
json_validate('{oops}');
echo json_last_error_msg(), "\n";
// JSON_THROW_ON_ERROR leaves the global error state alone
json_decode('[1, 2]', flags: JSON_THROW_ON_ERROR);
echo json_last_error_msg(), "\n"; // still the old error
// any call without the flag resets it
json_validate('[1, 2]');
echo json_last_error_msg(), "\n";
Output:
Syntax error
Syntax error
No error
json_validate vs json_decode: memory and speed
The main reason to use json_validate() is memory. json_decode() has to create every array, string and number in the document. json_validate() only scans the input. The script below checks a 9.5 MB document both ways:
<?php
// Build a ~9.5 MB JSON document with 100,000 records
$rows = [];
for ($i = 0; $i < 100_000; $i++) {
$rows[] = ['id' => $i, 'name' => "user$i", 'email' => "user$i@example.com",
'tags' => ['a', 'b', 'c'], 'active' => $i % 2 === 0];
}
$json = json_encode($rows);
unset($rows);
printf("JSON size: %.1f MB\n", strlen($json) / 1024 / 1024);
function measure(string $label, callable $fn): void
{
memory_reset_peak_usage();
$before = memory_get_usage();
$start = hrtime(true);
$fn();
printf("%-14s %6.1f ms, peak extra memory %5.1f MB\n", $label,
(hrtime(true) - $start) / 1e6,
(memory_get_peak_usage() - $before) / 1024 / 1024);
}
measure('json_validate', function () use ($json) {
$ok = json_validate($json);
});
measure('json_decode', function () use ($json) {
$data = json_decode($json, true);
$ok = json_last_error() === JSON_ERROR_NONE;
});
Output (timings vary between runs and machines):
JSON size: 9.5 MB
json_validate 210.1 ms, peak extra memory 0.0 MB
json_decode 240.6 ms, peak extra memory 93.3 MB
The decoded array takes about 10 times the size of the JSON text. json_validate() needs almost no extra memory. That matters when the input is large or when memory_limit is tight: decoding a big document can hit a fatal "Allowed memory size exhausted" error, and validating it won't.
The speed difference is smaller. The same parser does most of the work in both cases, and json_validate() only skips building the values. Both stop at the first error, so an input that is broken near the start is rejected almost immediately.
Limiting nesting with $depth
$depth is the maximum nesting depth, and it works exactly like the $depth parameter of json_decode(). A document with n levels of nested arrays or objects needs a depth of at least n + 1:
<?php
$json = '{"user": {"address": {"city": "Oslo"}}}'; // 3 levels of nesting
foreach ([1, 2, 3, 4] as $depth) {
$ok = json_validate($json, $depth);
printf("depth %d: %s\n", $depth, $ok ? 'valid' : json_last_error_msg());
}
// A scalar has no nesting, so depth 1 is enough
var_dump(json_validate('"hello"', 1));
Output:
depth 1: Maximum stack depth exceeded
depth 2: Maximum stack depth exceeded
depth 3: Maximum stack depth exceeded
depth 4: valid
bool(true)
A document that is too deep fails with JSON_ERROR_DEPTH. Use a low limit on untrusted input: if your API never nests more than a few levels, it has no reason to accept 500.
<?php
// An attacker sends 1,000 nested arrays
$hostile = str_repeat('[', 1000) . str_repeat(']', 1000);
var_dump(json_validate($hostile)); // default depth is 512
echo json_last_error_msg(), "\n";
// Your API never nests more than a few levels, so be strict
$maxDepth = 16;
var_dump(json_validate('{"items": [{"id": 1}]}', $maxDepth));
var_dump(json_validate(str_repeat('[', 20) . str_repeat(']', 20), $maxDepth));
Output:
bool(false)
Maximum stack depth exceeded
bool(true)
bool(false)
$depth must be greater than 0 and less than PHP_INT_MAX. A large $depth doesn't remove every limit, though. The parser has its own internal stack limit. With PHP 8.5, both json_validate() and json_decode() reject a document with 5,000 levels of nesting with "Syntax error", even when $depth allows it.
The JSON_INVALID_UTF8_IGNORE flag
$flags accepts only one flag, JSON_INVALID_UTF8_IGNORE. With it, invalid UTF-8 bytes inside strings are ignored instead of making the document invalid. Use it only if you will also decode with the same flag, because json_decode() then drops those bytes:
<?php
$json = "{\"name\": \"Jos\xE9\"}"; // invalid UTF-8 byte inside a string
var_dump(json_validate($json));
echo json_last_error_msg(), "\n";
var_dump(json_validate($json, flags: JSON_INVALID_UTF8_IGNORE));
// The same flag makes json_decode drop the bad byte
var_dump(json_decode($json, true, flags: JSON_INVALID_UTF8_IGNORE));
Output:
bool(false)
Malformed UTF-8 characters, possibly incorrectly encoded
bool(true)
array(1) {
["name"]=>
string(3) "Jos"
}
Any other flag, and an invalid depth, throws a ValueError. This includes JSON_THROW_ON_ERROR: json_validate() never throws for bad JSON. It returns false.
<?php
$tries = [
fn() => json_validate('[]', 0),
fn() => json_validate('[]', flags: JSON_THROW_ON_ERROR),
fn() => json_validate('[]', flags: JSON_INVALID_UTF8_SUBSTITUTE),
];
foreach ($tries as $try) {
try {
$try();
} catch (ValueError $e) {
echo $e->getMessage(), "\n";
}
}
Output:
json_validate(): Argument #2 ($depth) must be greater than 0
json_validate(): Argument #3 ($flags) must be a valid flag (allowed flags: JSON_INVALID_UTF8_IGNORE)
json_validate(): Argument #3 ($flags) must be a valid flag (allowed flags: JSON_INVALID_UTF8_IGNORE)
The first parameter is a string. With strict_types=1, passing an int throws a TypeError. Without it, passing null emits a deprecation notice and returns false.
When to use json_validate
Use json_validate() when you check JSON now and either decode it later somewhere else or never decode it in PHP at all. Typical cases:
- storing a raw JSON payload in a database column, cache or queue
- passing a body on to another service unchanged
- checking a config file or fixture in a test or lint step
- rejecting bad requests early, before they reach expensive code
Here a webhook endpoint stores payloads for a background worker. It only needs to know the body is well-formed:
<?php
// Webhook payloads are stored as-is and processed later by a worker.
// The receiver only needs to know the body is well-formed JSON.
function acceptWebhook(string $body, array &$queue): int
{
if (strlen($body) > 1_000_000) {
return 413; // Payload Too Large
}
if (!json_validate($body, 64)) {
error_log('rejected webhook: ' . json_last_error_msg());
return 400; // Bad Request
}
$queue[] = $body; // store the raw string, no decoding
return 202; // Accepted
}
$queue = [];
// in a real endpoint: $body = file_get_contents('php://input');
foreach (['{"event": "order.paid", "id": 7}', '{"event": "order.paid", "id": 7'] as $body) {
echo acceptWebhook($body, $queue), "\n";
}
echo count($queue), " payload(s) queued\n";
Output (the second line comes from error_log(), which writes to stderr in the CLI):
202
rejected webhook: Syntax error
400
1 payload(s) queued
When to decode directly with JSON_THROW_ON_ERROR
If you need the data right away, don't validate first. Calling json_validate() and then json_decode() parses the document twice. Decode once with JSON_THROW_ON_ERROR and catch JsonException:
<?php
$body = '{"name": "Ann", "roles": ["admin"]}';
// Don't: this parses the document twice
if (json_validate($body)) {
$data = json_decode($body, true);
}
// Do: decode once and let it throw on bad input
try {
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
echo "hello {$data['name']}\n";
} catch (JsonException $e) {
echo "bad JSON: {$e->getMessage()} (code {$e->getCode()})\n";
}
try {
json_decode('{"name": "Ann"', true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "bad JSON: {$e->getMessage()} (code {$e->getCode()})\n";
}
Output:
hello Ann
bad JSON: Syntax error (code 4)
The exception's code is the same JSON_ERROR_* value that json_last_error() would return.
Valid JSON is not valid data
json_validate() checks syntax only. It doesn't care about the shape of the document, the types of its values, duplicate keys or numbers too big for an int. After decoding you still need to check the data, by hand or with a JSON Schema library:
<?php
// All valid JSON, none of it a valid user record
$samples = [
'{"id": 1, "id": 2}', // duplicate key
'{"id": 123456789012345678901234567890}', // too big for int
'[]', // wrong shape
'{"id": "one"}', // wrong type
];
foreach ($samples as $s) {
$user = json_decode($s, true, 8, JSON_THROW_ON_ERROR);
$okShape = is_array($user) && is_int($user['id'] ?? null);
printf("%-42s valid=%s usable=%s\n", $s,
json_validate($s) ? 'yes' : 'no', $okShape ? 'yes' : 'no');
}
Output:
{"id": 1, "id": 2} valid=yes usable=yes
{"id": 123456789012345678901234567890} valid=yes usable=no
[] valid=yes usable=no
{"id": "one"} valid=yes usable=no
The duplicate key passes both checks. json_decode() silently keeps the last value, so id becomes 2. The big number decodes to a float.
A polyfill for PHP before 8.3
Libraries that support older PHP versions can define the function themselves. The symfony/polyfill-php83 package does this. The idea is simple:
<?php
if (!function_exists('json_validate')) {
function json_validate(string $json, int $depth = 512, int $flags = 0): bool
{
if ($flags !== 0 && $flags !== JSON_INVALID_UTF8_IGNORE) {
throw new ValueError('json_validate(): Argument #3 ($flags) must be a valid flag (allowed flags: JSON_INVALID_UTF8_IGNORE)');
}
if ($depth <= 0) {
throw new ValueError('json_validate(): Argument #2 ($depth) must be greater than 0');
}
json_decode($json, null, $depth, $flags);
return json_last_error() === JSON_ERROR_NONE;
}
}
The polyfill gives the same answers and sets the same error state, but it decodes the document, so you don't get the memory savings. Those come only from the native function in PHP 8.3+.
Summary
json_validate($json)returnstrueif the string is valid JSON, without building PHP values.- After a
falseresult, usejson_last_error()andjson_last_error_msg()to get the reason. - It uses almost no extra memory. It is only a little faster than
json_decode(). $depthlimits nesting the same way as injson_decode(). Keep it low for untrusted input.- The only allowed flag is
JSON_INVALID_UTF8_IGNORE. Other flags throwValueError. - If you need the data, skip validation and call
json_decode()withJSON_THROW_ON_ERROR. - Valid syntax doesn't mean valid data. Check the decoded shape and types too.