解决方案 3(最快的方法)
/**
* @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;
}
}
你可以使用它:
var myJson = [{"user":"chofoteddy"}, {"user":"bart"}];
isJSON(myJson); // true
验证对象是否为 JSON 或数组类型的最佳方法如下:
var a = [],
o = {};
解决方案 1
toString.call(o) === '[object Object]'; // true
toString.call(a) === '[object Array]'; // true
解决方案 2
a.constructor.name === 'Array'; // true
o.constructor.name === 'Object'; // true
但是,严格来说,数组是 JSON 语法的一部分。因此,以下两个示例是 JSON 响应的一部分:
console.log(response); // {"message": "success"}
console.log(response); // {"user": "bart", "id":3}
还有:
console.log(response); // [{"user":"chofoteddy"}, {"user":"bart"}]
console.log(response); // ["chofoteddy", "bart"]
AJAX/JQuery(推荐)
如果您使用 JQuery 通过 AJAX 带来信息。我建议您将“json”值放入“dataType”属性中,这样无论您是否获得 JSON,JQuery 都会为您验证它并通过它们的“成功”和“错误”函数使其知道。示例:
$.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) {}
});