The function introduced in PHP 8.3 provides a more efficient way to check if a given string is valid JSON compared to the previous approach of using json_decode
and checking for errors. The new function json_validate
uses the same underlying JSON parser as PHP, which consumes less memory and processing power by only analyzing the string without constructing any decoded value.
that returns json_validate
true
or false
whether the given string is a valid JSON string.
Example:
<?php
json_validate('[1, 2, 3]'); // true
json_validate('{1, 2, 3]'); // false
<?php
if (json_validate($jsonString) === false) {
throw new \JsonException(
json_last_error_msg(),
json_last_error()
);
}
json_validate function synopsis:
json_validate
is declared in the global namespace. And validation errors can be retrieved with the existing json_last_error
and json_last_error_msg
functions.
<?php
/**
* Validates a given string to be valid JSON.
*
* @param string $json String to validate
* @param int $depth Set the maximum depth. Must be greater than zero.
* @param int $flags Bitmask of flags.
* @return bool True if $json contains a valid JSON string, false otherwise.
*/
function json_validate(string $json, int $depth = 512, int $flags = 0): bool {
}