Jquery 如何检查值是否为JSON对象?
我的服务器端代码在成功时返回一个JSON对象值,在失败时返回一个字符串“false”。现在,我如何检查返回的值是否是JSON对象?您应该始终返回JSON,但更改其状态,或者在以下示例中更改响应代码属性:Jquery 如何检查值是否为JSON对象?,jquery,json,object,Jquery,Json,Object,我的服务器端代码在成功时返回一个JSON对象值,在失败时返回一个字符串“false”。现在,我如何检查返回的值是否是JSON对象?您应该始终返回JSON,但更改其状态,或者在以下示例中更改响应代码属性: if(callbackResults.ResponseCode!="200"){ /* Some error, you can add a message too */ } else { /* All fine, proceed with code */ }; 既然它只是fal
if(callbackResults.ResponseCode!="200"){
/* Some error, you can add a message too */
} else {
/* All fine, proceed with code */
};
既然它只是false和json对象,为什么不检查它是否为false,否则它必须是json
if(ret == false || ret == "false") {
// json
}
如果要显式测试有效的JSON(而不是没有返回值
false
),则可以使用所述的解析方法。jQuery.parseJSON()应返回类型为“object”的对象,如果字符串是JSON,则只需使用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
}
}
实际上对我不起作用,因为我有
"Unexpected Token <"
正如我之前说过的,如果您从AJAX请求返回字符串类型的内容,或者如果您返回混合类型,那么这就是解决方案 我知道这个线程已经被回答了,但是来到这里并没有真正解决我的问题,我在其他地方找到了这个函数。 也许来这里的人会发现它对他们有些用处
function getClass(obj) {
if (typeof obj === "undefined")
return "undefined";
if (obj === null)
return "null";
return Object.prototype.toString.call(obj)
.match(/^\[object\s(.*)\]$/)[1];
}
如果您有jQuery,请使用
解决方案3(最快方式)
您可以使用它:
var myJson = [{"user":"chofoteddy"}, {"user":"bart"}];
isJSON(myJson); // true
验证对象是否为JSON或array类型的最佳方法如下:
var a = [],
o = {};
解决方案1
解决方案2
但是,严格来说,数组是JSON语法的一部分。因此,以下两个示例是JSON响应的一部分:
console.log(response); // {"message": "success"}
console.log(response); // {"user": "bart", "id":3}
以及:
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) {}
});
我真的不喜欢被接受的答案。首先,它需要jQuery,而jQuery并不总是可用或必需的。第二,它把我认为过分的对象完全严格化了。这里有一个简单的函数,它完全检测一个值是否类似于JSON,只使用库中的几个部分来实现泛型
import * as isNull from 'lodash/isNull'
import * as isPlainObject from 'lodash/isPlainObject'
import * as isNumber from 'lodash/isNumber'
import * as isBoolean from 'lodash/isBoolean'
import * as isString from 'lodash/isString'
import * as isArray from 'lodash/isArray'
function isJSON(val) {
if (isNull(val)
|| isBoolean(val)
|| isString(val))
return true;
if (isNumber(val))
return !isNaN(val) && isFinite(val)
if (isArray(val))
return Array.prototype.every.call(val, isJSON)
if (isPlainObject(val)) {
for (const key of Object.keys(val)) {
if (!isJSON(val[key]))
return false
}
return true
}
return false
}
我甚至花时间将它作为一个包放到npm中:。将它与类似的东西一起使用,以便在浏览器中获取它
希望这对别人有帮助 我用它来验证JSON对象
function isJsonObject(obj) {
try {
JSON.parse(JSON.stringify(obj));
} catch (e) {
return false;
}
return true;
}
我用它来验证JSON字符串
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
我尝试了所有建议的答案,但没有任何效果,所以我不得不使用
jQuery.isEmptyObject()
为了帮助其他人解决这个问题@bart,您可以在if条件下提供对象,这将进行检查。如果它实际上是“您的”服务器端代码,为什么不在JSON结果中设置一个状态字段,而不是创建“有时是-JSON-有时是-it-not”的情况…?@出于调试原因。现在,您永远不会知道服务器将抛出哪种类型的故障,也不会使用json。我仍然不认为在服务器响应中使用错误代码(作为命名字段)会破坏这一点。这对Freebase来说已经足够好了!如果可以的话,请将接受的答案更改为Serguei Federov的答案。当前接受的答案不正确。什么是“json对象”?有JSON字符串和JS对象,但没有“JavaScript对象表示法对象”这样的东西。如果在jQuery 1.9之前,parseJSON可能要处理JSON值(即HTML)以外的内容,则可能还需要对异常使用try/catch,$.parseJSON返回null,而不是在传递空字符串、null或未定义时抛出错误,即使这些字符串不是有效的JSON。此解决方案不是最好的,因为return
“SyntaxError:JSON.parse:unexpected character”
error,我认为最好的解决方案是使用Serguei Fedorov在这里说的try/catch:如果你不想使用jquery,你可以通过检查这里描述的构造函数类型来使用vanilla JS:这个答案不正确,Serguei Federov的答案应该是可接受的答案。如果你在字符串上使用isPlainObject,它返回false,例如jQuery.isPlainObject(“{}”)更重要的是,如果它包含一个类似于JSON的值作为属性,根据文档,这个函数仍然会返回true
。问题不在于任何一点上的非JSON字符串。服务器总是返回有效的JSON(字符串false
也是有效的JSON)。问题只涉及一点:如何区分解析的JSON字符串是布尔值false
还是objectPerformance考虑因素:将其包装在函数中,确保不要解析JSON两次(一次在try-catch中,一次在调用函数的代码中)这是一个可以使用的helpers函数:isJSON(someValue)
。
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({
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) {}
});
var checkJSON = function(m) {
if (typeof m == 'object') {
try{ m = JSON.stringify(m); }
catch(err) { return false; } }
if (typeof m == 'string') {
try{ m = JSON.parse(m); }
catch (err) { return false; } }
if (typeof m != 'object') { return false; }
return true;
};
checkJSON(JSON.parse('{}')); //true
checkJSON(JSON.parse('{"a":0}')); //true
checkJSON('{}'); //true
checkJSON('{"a":0}'); //true
checkJSON('x'); //false
checkJSON(''); //false
checkJSON(); //false
import * as isNull from 'lodash/isNull'
import * as isPlainObject from 'lodash/isPlainObject'
import * as isNumber from 'lodash/isNumber'
import * as isBoolean from 'lodash/isBoolean'
import * as isString from 'lodash/isString'
import * as isArray from 'lodash/isArray'
function isJSON(val) {
if (isNull(val)
|| isBoolean(val)
|| isString(val))
return true;
if (isNumber(val))
return !isNaN(val) && isFinite(val)
if (isArray(val))
return Array.prototype.every.call(val, isJSON)
if (isPlainObject(val)) {
for (const key of Object.keys(val)) {
if (!isJSON(val[key]))
return false
}
return true
}
return false
}
function isJsonObject(obj) {
try {
JSON.parse(JSON.stringify(obj));
} catch (e) {
return false;
}
return true;
}
function isJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
jQuery.isEmptyObject()