PHP check if a string is JSON

Simple method will be:

if( is_array(json_decode($string,true)) ){
    echo true;
}
else{
    echo false;
}

This method doesn’t rely on heuristics, uses native php functionality, and is about as future-proof as you’re gonna get; it just tells you straight up whether there were any errors in decoding the string.


function isJson($string) {
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

By Keenlio, April 7, 2014

What do you think?

Leave a Reply

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


× 6 = thirty six

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>