How to get a count back for my json?
I have a response coming back from my server that looks like this
{"Errors":{"ViewModels[0]":"Not a valid number."},"IsValid":false,"SuccessMessage":null}
I want to loop through all the values contrained in Errors(in this case there is only one but there could many).
I tried
function createErrorList(response)
{
for (var i = 0; i < response.Errors.length; i++)
{
var error = response.Errors[i];
开发者_StackOverflow alert(error);
}
}
length is alwasy undefined though. So I am not sure what I am doing wrong.
Errors is not an array it's an object in this case. The server response would have to be something like:
{"Errors":[{"ViewModels[0]":"Not a valid number."},{"viewmodels[1]":"Another Message"}],"IsValid":false,"SuccessMessage":null}
For that to work. Note the [].
for( var key in response.Errors ) {
var value = response.Errors[key];
}
for (var error in response.Errors)
{
alert(response.Errors[error]);
}
You may also want to include hasOwnProperty if you are paranoid about prototypes on the Object object.
response.Errors is a dictionary not a list so you have to iterate through as such
精彩评论