Check If A String Is JSON in PHP

PHP

Read {count} times since 2020

In my previous post, I gave the isHTML function that returns if a string is HTML or not. In this post, I will give you a simple function of different ways that helps in the detection of valid JSON string in PHP. The function I’m giving are fast, easy and doesn’t take up too much CPU memory.

Method 1

JSON (JavaScript Object Notation) can be made in to a PHP object using json_decode. If the return is not an object, the string we gave is not JSON. This is the principal of Method 1 function.

function isJSON($string){
   return is_string($string) && is_array(json_decode($string, true)) ? true : false;
}

Method 2

Requires PHP versions 5.3 or more.

function isJSON($string){
   return is_string($string) && is_array(json_decode($string, true)) && (json_last_error() == JSON_ERROR_NONE) ? true : false;
}

Method 2 does 3 checks for calculating if the string given to it is JSON. So, it is the most perfect one, but it’s slower than the other.

Usage

If you have used any methods, the usage is the same.

Checking when the string given is perfectly valid :

$string = '{"host" : "demos.subinsb.com"}';
if(isJSON($string)){
 echo "It's JSON";
}

The above code when executed will echoes It’s JSON.**

**

Checking when the string given is not valid :

$string = '{"host : "demos.subinsb.com"}do you think this is valid ?';
if(!isJSON($string)){
 echo "Not JSON";
}

The above code when executed will print Not JSON.