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

bart picture bart · Nov 28, 2010 · Viewed 207.3k times · Source

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?

Answer

Serguei Fedorov picture Serguei Fedorov · Aug 31, 2012

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.