我有以下json返回。我希望得到汽车,汽车,汽车和汽车的所有价值。价格。怎么做到呢?我试过这个但没有工作
$.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."
]
}
}
答案 0 :(得分:2)
你会得到3个这样的值:
alert(json.ModelState["car"]);
alert(json.ModelState["car.Make"]);
alert(json.ModelState["car.Price"]);
这也适用于汽车
alert(json.ModelState.car);
由于其他属性包含'。'然后它在名称中查找属性Make而不是属性car.Make因此我们需要使用字符串键。
请注意,在这个小提琴中,最后两个是未定义的。最好不要使用'。'属性名称,如果将在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]);
}
}
答案 1 :(得分:0)
拥有一个带有JSON的变量:
var obj= {
"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."
]
}
};
通过ModelState进行循环访问:
for (var prop in obj.ModelState){
for (var i=0; i<obj.ModelState[prop].length; i++){
console.log(obj.ModelState[prop][i]);
}
}
小提琴:http://jsfiddle.net/m8gq0Lew/2/
还建议不要在JSON密钥中使用.