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?
Solution 1:
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.
Solution 2:
jQuery.parseJSON() should return an object of type "object", if the string was JSON, so you only have to check the type with typeof
var response=jQuery.parseJSON('response from server');
if(typeof response =='object')
{
// It is JSON
}
else
{
if(response ===false)
{
// the response was a string "false", parseJSON will convert it to boolean false
}
else
{
// the response was something else
}
}
Solution 3:
Solution 3 (fastest way)
/**
* @param Object
* @returns boolean
*/
function isJSON (something) {
if (typeof something != 'string')
something = JSON.stringify(something);
try {
JSON.parse(something);
return true;
} catch (e) {
return false;
}
}
You can use it:
var myJson = [{"user":"chofoteddy"}, {"user":"bart"}];
isJSON(myJson); // true
The best way to validate that an object is of type JSON or array is as follows:
var a = [],
o = {};
Solution 1
toString.call(o) === '[object Object]'; // true
toString.call(a) === '[object Array]'; // true
Solution 2
a.constructor.name === 'Array'; // true
o.constructor.name === 'Object'; // true
But, strictly speaking, an array is part of a JSON syntax. Therefore, the following two examples are part of a JSON response:
console.log(response); // {"message": "success"}
console.log(response); // {"user": "bart", "id":3}
And:
console.log(response); // [{"user":"chofoteddy"}, {"user":"bart"}]
console.log(response); // ["chofoteddy", "bart"]
AJAX / JQuery (recommended)
If you use JQuery to bring information via AJAX. I recommend you put in the "dataType" attribute the "json" value, that way if you get a JSON or not, JQuery validate it for you and make it known through their functions "success" and "error". Example:
$.ajax({
url: 'http://www.something.com',
data: $('#formId').serialize(),
method: 'POST',
dataType: 'json',
// "sucess" will be executed only if the response status is 200 and get a JSON
success: function (json) {},
// "error" will run but receive state 200, but if you miss the JSON syntax
error: function (xhr) {}
});
Solution 4:
If you have jQuery, use isPlainObject.
if ($.isPlainObject(my_var)) {}