Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a value is a JSON object?

My server side code returns a value which is a JSON object on success and a string 'false' on failure. Now how can I check whether the returned value is a JSON object?

like image 465
bart Avatar asked Nov 28 '10 04:11

bart


People also ask

How do you check if value is JSON or not?

In order to check the validity of a string whether it is a JSON string or not, We're using the JSON. parse()method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.

How do you check if a key exists in JSON object and get its value?

Use below code to find key is exist or not in JsonObject . has("key") method is used to find keys in JsonObject . If you are using optString("key") method to get String value then don't worry about keys are existing or not in the JsonObject . Note that you can check only root keys with has(). Get values with get().


1 Answers

The chosen solution doesn't actually work for me because I get a

     "Unexpected Token <"  

error in Chrome. This is because the error is thrown as soon as the parse comes across and unknown character. However, there is a way around this if you are returning only string values through ajax (which can be fairly useful if you are using PHP or ASPX to process ajax requests and might or might not return JSON depending on conditions)

The solution is quite simple, you can do the following to check if it was a valid JSON return

       var IS_JSON = true;        try        {                var json = $.parseJSON(msg);        }        catch(err)        {                IS_JSON = false;        }                 

As I have said before, this is the solution for if you are either returning string type stuff from your AJAX request or if you are returning mixed type.

like image 65
Serguei Fedorov Avatar answered Sep 23 '22 16:09

Serguei Fedorov