我有以下 json 返回。我希望获得汽车、汽车制造商和汽车价格的所有值(value)。如何做呢?我已经尝试过但不起作用
$.each(jqXHR.responseJSON.ModelState(index, value), function() {
alert(jqXHR.responseJSON.ModelState[index].value);
});
{
"Message": "The request is invalid.",
"ModelState": {
"car": [
"Required property 'Make' not found in JSON. Path '', line 1, position 57."
],
"car.Make" : [
"The Make field is required."
],
"car.Price": [
"The field Price must be between 0 and 200000."
]
}
}
最佳答案
您将得到如下 3 个值:
alert(json.ModelState["car"]);
alert(json.ModelState["car.Make"]);
alert(json.ModelState["car.Price"]);
这也适用于汽车
alert(json.ModelState.car);
由于其他属性包含“.”然后它会在属性 car 上查找属性 Make,而不是名为 car.Make 的属性,因此我们需要使用字符串键。
请注意,在此 fiddle 中,最后两个未定义。最好不要使用“.”属性名称(如果要在 json 中使用)。
https://jsfiddle.net/1zgybf9m/
打印 modelState 中的所有数据和所有汽车,假设您可以拥有不止一辆。 IT 会更像这样:
https://jsfiddle.net/1zgybf9m/1/
var json = {
"Message": "The request is invalid.",
"ModelState": {
"car": [
"1 Required property 'Make' not found in JSON. Path '', line 1, position 57.",
"2 Required property 'Make' not found in JSON. Path '', line 1, position 57."
],
"car.Make" : [
"1 The Make field is required.",
"2 The Make field is required."
],
"car.Price": [
"1 The field Price must be between 0 and 200000.",
"2 The field Price must be between 0 and 200000."
]
}
}
for(var prop in json.ModelState){
console.log(prop);
for(var value in json.ModelState[prop]){
console.log(json.ModelState[prop][value]);
}
}
关于javascript - 从嵌套响应中获取 json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33411787/