More

New json_validate method in PHP 8.3

If you have experience in working with APIs or currently working with or developing the APIs you will know that JSON is now the standard of communication between two endpoints.

When you are creating new APIs it most common thing you have to deal with is malformed JSON strings, to handle malformed JSON we used to do something like this.

$jsonString = "{ "email" : "jhon@doe.com" } ";
$jsonData = json_decode($jsonString);
if(json_last_error() == JSON_ERROR_NONE) {
    // json is valid
} else {
   // json is invalid
}

or you wrap your code between try and catch like the following code snippet.

try {
  $jsonString = "{ "email" : "jhon@doe.com" }";
  $jsonData = json_decode($jsonString, true, 512, JSON_THROW_ON_ERROR);
} catch(\Exception $e) {
    // handle exception 
}

From the 2 code examples given above, you can see that it’s a bit tiresome and not readable which is why in PHP 8.3 we are getting a new method called json_validate(). This new function will make a developer’s life a bit easier and code more readable while working with the JSON data. Once this method is available your code will look something like this.

$jsonString = "{ "email" : "jhon@doe.com" } ";
if(json_validate($jsonString)) {
   // do somethng
} else {
   // return error.
}

Much more readable than previous examples, isn’t it? json_validate() will return TRUE if the JSON string is valid otherwise FALSE. the following is the signature of the new json_validate method.

json_validate(string $json, int $depth = 512, int $flags = 0): bool
ParametersDescription
$jsonthe JSON string to be checked.
$depththe maximum number of depths greater than 0 to be checked.
$flagBismark of flags, check predefined constant page or json_decode documentation.

The json_valdiate will be using the exact same JSON parser which already exists in the PHP code, which is used by json_decode that ensures that what is valid in json_validate is also valid in json_decode.

The json_validate function is already implemented and we will able to use it from PHP version 8.3. if you want to know more about the RFC you can read the official PHP site.

E