Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether a string is valid JSON?

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.

like image 894
Spot Avatar asked Jul 27 '09 10:07

Spot


People also ask

What is a valid JSON string?

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.

How do you check if a string is a valid JSON string in Java?

Validating with JSONObject String json = "Invalid_Json"; assertFalse(validator. isValid(json));

Is a single string valid JSON?

A JSON value MUST be an object, array, number, or string, or one of the following three literal names: false null true".

How do you check if a file is a valid JSON?

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.


2 Answers

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.

like image 60
Daff Avatar answered Sep 21 '22 20:09

Daff


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)"; } 
like image 43
cgaldiolo Avatar answered Sep 19 '22 20:09

cgaldiolo