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.
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
With PHP >= 5.3
Usage example:
What about using
json_decode
, which should returnnull
if the given string was not valid JSON-encoded data ?See example 3 on the manual page :
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
returnsnull
anyway.Doesn't
json_decode()
with ajson_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.