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:

Download  Run Code

 
The predefined constant JSON_ERROR_NONE is equivalent to the integer 0. Therefore, the above function is equivalent to the following:

 
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.

Download  Run Code

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.

Download  Run Code

That’s all about checking if a string is JSON in PHP.