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.
JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.
Validating with JSONObject String json = "Invalid_Json"; assertFalse(validator. isValid(json));
A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true".
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema.
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.6 function is_JSON(...$args) { json_decode(...$args); return (json_last_error()===JSON_ERROR_NONE); }
With PHP >= 5.3
// PHP >= 5.3 function 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)"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With