Check if the data is JSON encoded or not.

Previously I had gone through the function to create a slug from the given string.

Today, I came up with a problem. Using Jquery I used the same function to send two types of value: one being a string and another JSON encoded. Now I had to check them and use methods accordingly.

For this, I searched for the solution and came to a StackOverflow solution. However, for better understanding, I found another blog that suggested several methods.
Click here for the blog.

The solution I used is, I passed the data through the function

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

and used if-else to use the method accordingly

if($this->isJSON($string)) {
        $string = json_decode($hotspot);
       //something to be done
}
else {
    //something to be done
}

Another solution that I was suggested from Reddit is to make a function that checks the data by decoding it, if it is successfully decoded, it returns the decoded data otherwise it returns the original data itself.

function json_try_decode($json) {
    if (! is_string($json)) {
        return $json;
    }

    $result = json_decode($json);

    return $result === false
        ? $json
        : $result;
}

I hope this helps you with your problems too.

508 thoughts on “Check if the data is JSON encoded or not.”

  1. Wow, fantastic blog structure! How lengthy have you been running a blog for?
    you make blogging look easy. The total look
    of your web site is great, as well as the content material!

Leave a Comment

Your email address will not be published. Required fields are marked *

Tweet
Share
Share
Pin