tags:

views:

669

answers:

6

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, but that seems a bit overkill.

+2  A: 

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
A: 

Well if you you need a "bullet proof" solution I think you have to (try) evaluate the whole string first. You could do a qualified guess by checking some characters. You know that the first char has to be { for a string to be valid json.

Kimble
+5  A: 

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 false anyway.

Daff
Yeah, I am an idiot. This was obvious and I just missed it. I can wrap this up into what I need. Thanks.
Spot
+2  A: 

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.

Kitson
A: 

This is actually a valid issue, that needs more of a solution than just using json_decode and hoping for an error. If you have a site with millions of users, and you are counting on spamming your error_log with this, it's gonna cause problems.

Looking for the leading '{' isn't good, because there can be leading '[' and leading '[[[' even.

I think we are looking for a perl-style regex to validate. Anyone? :)

mulligan
A: 
McNally Paulo