我的服务器端代码成功时返回一个JSON对象的值,失败时返回一个字符串'false‘。现在如何检查返回值是否为JSON对象?
发布于 2010-11-28 14:20:21
如果字符串是JSON,那么jQuery.parseJSON()应该返回一个" object“类型的对象,所以您只需要用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
}
}
发布于 2012-08-31 22:16:14
The chosen solution实际上并不适合我,因为我得到了一个
"Unexpected Token <"
Chrome中的错误。这是因为一旦解析遇到未知字符,就会抛出错误。但是,如果您只通过ajax返回字符串值,那么有一种方法可以解决这个问题(如果您正在使用PHP或ASPX来处理ajax请求,并且可能根据条件返回JSON,这将非常有用)。
解决方案非常简单,您可以执行以下操作来检查它是否是有效的JSON返回
var IS_JSON = true;
try
{
var json = $.parseJSON(msg);
}
catch(err)
{
IS_JSON = false;
}
正如我之前所说的,如果您从AJAX请求中返回字符串类型的内容,或者如果您返回的是混合类型,这就是解决方案。
发布于 2015-07-20 12:04:09
解决方案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带来信息。我建议您在"dataType“属性中输入" JSON”值,这样无论您是否获得JSON,JQuery都会为您验证它,并通过它们的函数"success“和"error”使其可知。示例:
$.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) {}
});
https://stackoverflow.com/questions/4295386
复制相似问题