简体   繁体   中英

Getting json value from nested response

I have the following json return. I wish to get all the value in car, car.Make and car.Price. How can it be done? I have tried this but not working

 $.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." ] } }

You would get the 3 values like this:

alert(json.ModelState["car"]);
alert(json.ModelState["car.Make"]);
alert(json.ModelState["car.Price"]);

this will also work for car

alert(json.ModelState.car);

Since the other properties contain a '.' in the name then it looks for a property Make on property car rather than property called car.Make therefore we need to use the string key.

Notice in this fiddle the last two are undefined. Best not to use '.' property names if going to be used in json.

https://jsfiddle.net/1zgybf9m/

To print all data in modelState and all cars, assuming you can have more than one. IT would be more like this:

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]);
    }
}

Having a variable with the 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."
            ]
        }
    };

For loop access through ModelState:

for (var prop in obj.ModelState){
    for (var i=0; i<obj.ModelState[prop].length; i++){
        console.log(obj.ModelState[prop][i]);    
    }    
}

fiddle: http://jsfiddle.net/m8gq0Lew/2/

It is also recommended not to use . in JSON-keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM