47

Does anyone know of a robust (and bullet proof) is_JSON function snippet for PHP? I (obviously) have a situation where I need to know if a string is JSON or not.

Hmm, perhaps run it through a JSONLint request/response, but that seems a bit overkill.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Spot
  • 7,962
  • 9
  • 46
  • 55
  • 1
    Shoot; I had a bullet-proof solution handy, but it wasn't very robust, so I had to scrap it :P –  Jan 02 '12 at 00:25

7 Answers7

71

If you are using the built in json_decode PHP function, json_last_error returns the last error (e.g. JSON_ERROR_SYNTAX when your string wasn't JSON).

Usually json_decode returns null anyway.

Jacco
  • 23,534
  • 17
  • 88
  • 105
Daff
  • 43,734
  • 9
  • 106
  • 120
  • 3
    Yeah, I am an idiot. This was obvious and I just missed it. I can wrap this up into what I need. Thanks. – Spot Jul 27 '09 at 11:05
  • Solid solution in most cases, but be careful. json_decode can also parse e.g. numeric strings. A phone number in a string would be converted to an integer. However, this does not happen on every server. On my windows machine I'm getting integers, on the linux developing system I'm getting false. I assume it depends on your PHP installation and configuration – StoryTeller Jun 30 '15 at 15:16
  • As StoryTeller mentioned - json_decode("51232") evaluates to 51232, so may not be useful in all situations – Paul Preibisch Nov 13 '17 at 08:08
20

For my projects I use this function (please read the "Note" on the json_decode() docs).

Passing the same arguments you would pass to json_decode() you can detect specific application "errors" (e.g. depth errors)

With PHP >= 5.6

// PHP >= 5.6
function is_JSON(...$args) {
    json_decode(...$args);
    return (json_last_error()===JSON_ERROR_NONE);
}

With PHP >= 5.3

// PHP >= 5.3
function is_JSON() {
    call_user_func_array('json_decode',func_get_args());
    return (json_last_error()===JSON_ERROR_NONE);
}

Usage example:

$mystring = '{"param":"value"}';
if (is_JSON($mystring)) {
    echo "Valid JSON string";
} else {
    $error = json_last_error_msg();
    echo "Not valid JSON string ($error)";
}
cgaldiolo
  • 3,497
  • 1
  • 20
  • 17
  • I'm not an expert in PHP, but this solution doesn't seem very efficient, as when JSON decoding is required, it does it twice: once when testing if the string is valid JSON, and the second time when actually decoding it. It seems that it would be wiser to simply have this function only check the last JSON error, assuming that json_decode has already been executed. I welcome other opinions. – Liran H Jan 10 '16 at 21:28
  • Hi @LiranH, the original poster requested a 'is_JSON' function therefore I cannot assume within the function that json_decode was just executed on the requested string. In that case your function would be named 'is_last_json_decoded_string_a_JSON_string'. – cgaldiolo Jan 11 '16 at 20:05
  • That's fair enough @cgaldiolo – Liran H Jan 12 '16 at 09:12
  • Tried your Php < 5.6 answer and got this: `PHP Fatal error: func_get_args(): Can't be used as a function parameter`. Going to just define the param in the func def – Kellen Stuart Apr 05 '17 at 21:02
  • Hi @KolobCanyon, this is happening because you are using PHP < 5.3. My solution works only with PHP >= 5.3 because the function json_last_error() is available starting with that version. I'm updating the answer, thank you. – cgaldiolo Apr 14 '17 at 17:18
  • @cgaldiolo It's cool you know the versions that well; I just copy pasted the code and got that error, so thought I'd tell you – Kellen Stuart Apr 15 '17 at 04:52
  • @KolobCanyon this is my tool to check simple code against different versions: https://3v4l.org/ – cgaldiolo Apr 17 '17 at 02:47
17

What about using json_decode, which should return null if the given string was not valid JSON-encoded data ?

See example 3 on the manual page :

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid 
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
4

Doesn't json_decode() with a json_last_error() work for you? Are you looking for just a method to say "does this look like JSON" or actually validate it? json_decode() would be the only way to effectively validate it within PHP.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Kitson
  • 1,650
  • 1
  • 18
  • 36
4

This is the best and efficient way

function isJson($string) {
    return (json_decode($string) == null) ? false : true;
}
3
$this->post_data = json_decode( stripslashes( $post_data ) );
  if( $this->post_data === NULL )
   {
   die( '{"status":false,"msg":"The post_data parameter must be valid JSON"}' );
   }
McNally Paulo
  • 192
  • 1
  • 8
0

json_validate() will Be live in PHP 8.3

jcmargentina
  • 181
  • 1
  • 6