[英]How to determine if json object is serialized dictionary?
My application making an ajax POST to server, and if the server validation fails, server returns string
or Dictionary<string, object>
back to client. 我的应用程序对服务器进行了ajax POST,如果服务器验证失败,则服务器将string
或Dictionary<string, object>
返回给客户端。
So if server is sending Dictionary
then the serialized responseText
that jQuery is receiving something like 因此,如果服务器正在发送Dictionary
则jQuery正在接收类似的序列化responseText
"{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}"
i also have corresponding responseJSON
available on client side. 我也有相应的responseJSON
在客户端可用。
$.ajax({
cache: false,
type: 'POST',
url: url,
data: data
})
.fail(function (response, textStatus, errorThrown) {
if (response.status === '400') {
if ($.isArray(response.responseJSON)) {
$.each(response.responseJSON, function (index, value) {
//do something
})
}
else if ($.type(response.responseJSON) === 'string') {
// do something
}
}
}
The .isArray
method returns false when response is dictionary. 当响应为字典时, .isArray
方法返回false。 How do i determine if responseJSON is Dictionary
and how do i loop? 如何确定responseJSON是否为Dictionary
以及如何循环?
You try to interpret the response and see if it ends up being an object (or "Dictionary"). 您尝试解释该响应,然后查看它是否最终成为对象(或“字典”)。 If the response appears to be JSON, and the result of it is also an object ("Dictionary"), then you know the string was an object ("Dictionary"). 如果响应看起来是JSON,并且其结果也是一个对象(“ Dictionary”),则您知道该字符串是一个对象(“ Dictionary”)。
The code below should outline all necessary techniques for you to integrate it into your own code. 下面的代码应概述所有将其集成到自己的代码中的必要技术。
var thatResponseJson = "{\"Key1\":[\"Error Message 1\"],\"Key2\":[\"Error message 2\"]}";
try {
var result = JSON.parse(thatResponseJson);
if (result instanceof Array) {
// An Array
} else if (typeof result === 'object' && thatResponseJson[0] === '{') {
// Usually an object
} else if (typeof result === 'string') {
// A string
} else {
// Neither an Array, some other kind of object, or a string
}
} catch (err) {
// Not valid JSON
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.