I need a really, really fast method of checking if a string is JSON or not. I feel like this is not the best way:
function isJson($string) {
return ((is_string($string) &&
(is_object(json_decode($string)) ||
is_array(json_decode($string))))) ? true : false;
}
Any performance enthusiasts out there want to improve this method?
The custom function
Cases
Resources
https://gist.github.com/rafasashi/93d06bae83cc1a1f440b
I don't know about performance or elegance of my solution, but it's what I'm using:
Since all my JSON encoded strings start with {" it suffices to test for this with a RegEx. I'm not at all fluent with RegEx, so there might be a better way to do this. Also: strpos() might be quicker.
Just trying to give in my tuppence worth.
P.S. Just updated the RegEx string to
/^[\[\{]\"/
to also find JSON array strings. So it now looks for either [" or {" at the beginning of the string.Another simple way
Hi here's a little snippet from my library, in this first condition I'm just checking if the data is json then return it if correctly decoded, please note the substr usage for performance ( I haven't seen yet any json file not begining neither by { or [
Freshly-made function for PHP 5.2 compatibility, if you need the decoded data on success:
Usage:
Some tests:
Using
json_decode
to "probe" it might not actually be the fastest way. If it's a deeply nested structure, then instantiating a lot of objects of arrays to just throw them away is a waste of memory and time.So it might be faster to use
preg_match
and the RFC4627 regex to also ensure validity:The same in PHP:
Not enough of a performance enthusiast to bother with benchmarks here however.