Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

The new json_validate() function in PHP 8.3

Today, if we want to validate a JSON string in PHP, we can use the json_decode() function. Here’s how it works.

$json = '{"name": "John Doe"}';
$data = json_decode($json);

if (json_last_error() === JSON_ERROR_NONE) {
    // Valid JSON
} else {
    // Invalid JSON
}

As you can tell, we can first decode the JSON string using the json_decode() function and then check if the json_last_error() function returns JSON_ERROR_NONE (based on the last JSON decode) or not. If it returns JSON_ERROR_NONE, it means the JSON string is valid. Otherwise, it’s invalid.

But, this is not the best way to do it. In my opinion, it’s a bit cumbersome and not very readable.

Enter json_validate() function

And that’s why PHP 8.3 will be introducing a new json_validate() function that can be used to validate a JSON string. So, we can do something like this.

$json = '{"name": "John Doe"}';
$valid = json_validate($json);

if ($valid) {
    // Valid JSON
} else {
    // Invalid JSON
}

And that’s it! The json_validate() function returns true if the JSON string is valid and false if it’s invalid. No more relying on the json_last_error() function. It’s far more readable, straightforward, and easy to use.

Here’s the exact signature of the json_validate() function.

json_validate(string $json, int $depth = 512, int $flags = 0): bool
  • $json - The JSON string to validate.
  • $depth - The maximum nesting depth of the structure being decoded. Must be greater than zero.
  • $flags - Bitmask of JSON decode flags. See the json_decode() function for more details.

Behind the scenes

Under the hood, the json_validate() function uses the the exact same JSON parser that already exists in the PHP core, which is also use by json_decode(), this garantees that what is valid in json_validate() is also valid in json_decode().

You can read more about the json_validate() function in the RFC.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?