Check if String is Valid JSON using json_validate in PHP 8.3

Check if String is Valid JSON using json_validate in PHP 8.3

In PHP versions before 8.3, the only way to determine whether a provided string is a valid JSON was by attempting to decode it and examining any resulting error.

Since PHP 8.3, we can utilize the json_validate function to verify whether a given string is a valid JSON.

<?php

echo (int) json_validate('{"name":"John"}'); // 1
echo (int) json_validate('{0,1,3}'); // 0

The json_validate function employs PHP's existing JSON parser but operates more efficiently by consuming less memory. Unlike json_decode, it analyzes the string without the need to construct the array or object. Using json_validate right before json_decode results in redundant parsing of the string, since json_decode includes validation during the decoding process. So, it's recommended to use json_validate when only JSON validation is needed.

Leave a Comment

Cancel reply

Your email address will not be published.