How to determine whether a string is valid JSON?
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.
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.6function is_JSON(...$args) { json_decode(...$args); return (json_last_error()===JSON_ERROR_NONE);}
With PHP >= 5.3
// PHP >= 5.3function 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)";}
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