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 fastest way to maybe decode a possible JSON object to a PHP object/array:
All you really need to do is this...
This request does not require a separate function even. Just wrap is_object around json_decode and move on. Seems this solution has people putting way too much thought into it.
The function
json_last_error
returns the last error occurred during the JSON encoding and decoding. So the fastest way to check the valid JSON isNote that
json_last_error
is supported in PHP >= 5.3.0 only.It is always good to know the exact error during the development time. Here is full program to check the exact error based on PHP docs.
Since
json_last_error
is not supported in PHP 5.2, you can check if the encoding or decoding returns booleanFALSE
. Here is an exampleHope this is helpful. Happy Coding!
You must validate your input to make sure the string you pass is not empty and is, in fact, a string. An empty string is not valid JSON.
I think in PHP it's more important to determine if the JSON object even has data, because to use the data you will need to call
json_encode()
orjson_decode()
. I suggest denying empty JSON objects so you aren't unnecessarily running encodes and decodes on empty data.Expanding on this answer How about the following:
The simplest and fastest way that I use is following;
It is because json_decode() returns NULL if the entered string is not json or invalid json.
Simple function to validate JSON
If you have to validate your JSON in multiple places, you can always use the following function.
In the above function, you will get true in return if it is a valid JSON.