In PHP, json_validate() checks whether a string contains valid JSON. It returns true or false and does not build any PHP value. It is available in PHP 8.3 and later.
Before PHP 8.3 you had to call json_decode() just to find out if text was valid JSON, which wastes memory on big strings. json_validate() only checks the syntax, so it is faster and lighter when you do not need the decoded data.
Syntax
Call json_validate() with the values you need. Start with this line.
PHP
$isValid = json_validate($json);
Call
What it does
json_validate('{"a":1}')
Returns true because the JSON is valid.
json_validate('{a:1}')
Returns false because the key is not in double quotes.
json_validate($json, 5)
Returns true only if the JSON is valid and nested no deeper than 5 levels.
json_validate() requires PHP 8.3 or newer. It also updates json_last_error() and json_last_error_msg(), so you can find out why validation failed. The only flag it accepts is JSON_INVALID_UTF8_IGNORE.
Library declarations
PHP
json_validate(string $json, int $depth = 512, int $flags = 0): bool
Parameters
Parameter
Description
json
Required. The string to check. An empty string is not valid JSON.
depth
Optional. The maximum nesting depth allowed. The default is 512. It must be greater than 0, otherwise PHP throws a ValueError.
flags
Optional. The only supported flag is JSON_INVALID_UTF8_IGNORE. Any other flag throws a ValueError. The default is 0.
Return Value
Return Value
Description
bool
true if the string is valid JSON within the depth limit, otherwise false.
PHP Examples
Example 1 — Validate JSON Strings
Check a few strings and see which ones are valid JSON.
function_exists() checks whether json_validate() is available on this PHP version.
On PHP 8. 3 and newer the helper uses json_validate() directly.
On older versions it decodes the text and checks json_last_error() instead.
A plain JSON string in double quotes is valid JSON, so the last call prints Valid.
Frequently Asked Questions
It checks if a string is valid JSON and returns true or false. Unlike json_decode(), it does not create a PHP value, so it uses less memory.
It was added in PHP 8.3. On PHP 8.2 or older, calling it causes a fatal error, so use function_exists() or json_decode() with json_last_error() as a fallback.
json_validate() only answers yes or no. json_decode() actually builds the data. If you need the data anyway, just use json_decode() with JSON_THROW_ON_ERROR.
Yes. It updates the global JSON error state, so json_last_error() and json_last_error_msg() tell you the reason, such as a syntax error or a depth problem.
No. An empty string is not valid JSON, so json_validate('') returns false. A string that holds just a number, a quoted text, true, false or null is valid.