Check if a string is JSON in PHP
This article demonstrates how to check if a string is JSON in PHP.
1. Using json_decode() function
The idea is to decode the given string to JSON and check if any errors occurred during the decoding. You can use the json_decode() function to decode the JSON string. Then invoke the json_last_error() function to get the error that occurred during the decoding. If no error has occurred, the function returns JSON_ERROR_NONE. The following solution demonstrates this by validating JSON strings in PHP:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php function is_json_string($json_str) { json_decode($json_str); return json_last_error() === JSON_ERROR_NONE; } $json_str = '{"x":5,"y":6}'; if (is_json_string($json_str)) { echo 'JSON is valid'; } else { echo 'JSON is not valid'; } ?> |
The predefined constant JSON_ERROR_NONE is equivalent to the integer 0. Therefore, the above function is equivalent to the following:
|
1 2 3 4 5 |
function is_json_string($json_str) { json_decode($json_str); return json_last_error() === 0; } |
Alternatively, you can use the return value of the json_decode() function to check a string for valid JSON. It returns the JSON encoded value, or null if the JSON cannot be decoded. However, the solution needs an explicit check for the 'null' value, since json_decode() returns null for the 'null' string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php function is_json_string($json_str) { $json = json_decode($json_str); return $json_str === 'null' || $json !== null; } $json_str = '{"x":5,"y":6}'; if (is_json_string($json_str)) { echo 'JSON is valid'; } else { echo 'JSON is not valid'; } ?> |
2. Using preg_match() function
You can also use regular expressions to validate JSON strings in PHP. The following solution uses two regular expressions, taken from the RFC 4627 specification document, and calls to the preg_match() and preg_replace() functions.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php function is_json_string($json_str) { return !preg_match('/[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\ ]/', preg_replace('/"(\\.|[^"\\\\])*"/', '', $json_str)); } $json_str = '{"x":5,"y":6}'; if (is_json_string($json_str)) { echo 'JSON is valid'; } else { echo 'JSON is not valid'; } ?> |
That’s all about checking if a string is JSON in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)