json_validate
Checks whether a string is valid JSON.
Syntax
json_validate(string $json, int $depth = 512, int $flags = 0): boolParameters
| Parameter | Type | Description |
|---|---|---|
| $json | string | The string to check. |
| $depth | int | Optional. The maximum nesting. |
| $flags | int | Optional. Flags. |
Return value
bool`true` if the string is valid JSON.
Examples
Valid and invalid JSON:
<?php
var_dump(json_validate('{"name":"Anna"}'));
var_dump(json_validate("{'name':'Anna'}"));Output:
bool(true)
bool(false)Notes
The function appeared in PHP 8.3. It builds no array, so it is faster than calling json_decode() just to check.
See also
- json_decode — Parses a JSON string.
- json_last_error_msg — Returns the error description of the last `json_decode()` or `json_encode()` call.
- json_encode — Converts a value to a JSON string.
In the tutorial
- The JSON format — JSON in PHP — json_encode and json_decode, non-ASCII text, error handling and storing data in a file.