Reputation: 22556
here is an example of the JSON string:
[{"Description":"Administrators can do everything on the site","Id":"381ede0e-3bc1-4d71-83d8-bbb62a3b8aaa","Name":"Admin"},{"Description":"Technical users with limited permissions a","Id":"7a632af6-214b-4a8e-a3f8-9c0aafae2645","Name":"Technical"}]
here is my script so far:
//Get Users Roles:
$.getJSON('@Url.Action("GetAUsersRegisteredRoles")' + '/' + selectedUser, function (json) {
console.log('1:');
console.log(json);
//Parse JSON
$.each(json, function () {
$.each(this, function (k, v) {
alert(v.Id + v.Name +v.Description);
})
});
});
I know I am doing something wrong with the way that I am parsing it? Im sure its just something silly.
Here is the view of the json array in the console:
When I run it in the browser my alert popup comes 6 times and says NaN
I looked at: Link which helped me get to where I am now.
Upvotes: 1
Views: 140
Reputation: 272036
Your JSON is an array of objects:
[
{
"Description": "Administrators can do everything on the site",
"Id": "381ede0e-3bc1-4d71-83d8-bbb62a3b8aaa",
"Name": "Admin"
},
{
"Description": "Technical users with limited permissions a",
"Id": "7a632af6-214b-4a8e-a3f8-9c0aafae2645",
"Name": "Technical"
}
]
You only need to iterate over the top level:
$.each(json, function (k, v) {
console.log(v.Id, v.Name, v.Description);
});
PS: it often helps if you look directly at pretty-printed JSON.
Upvotes: 3
Reputation: 3039
That's fine. Just wrap this
with $
to jquerify it like $(this).
Here is the example:
var json = [
{
"Description":"Administrators can do everything on the site",
"Id":"381ede0e-3bc1-4d71-83d8-bbb62a3b8aaa",
"Name":"Admin"
},
{
"Description":"Technical users with limited permissions a",
"Id":"7a632af6-214b-4a8e-a3f8-9c0aafae2645",
"Name":"Technical"
}
];
$.each(json, function () {
$.each($(this), function (k, v) { // this ==> $(this) in this line
alert(v.Id + v.Name +v.Description);
})
});
Jsfiddle: http://jsfiddle.net/ashishanexpert/xL7jm/
or dont do the second loop, because you have reference of the entire object in the first loop only. like:
$.each(json, function (k, v) {
// Here v is that object each time of the loop
alert(v.Id + v.Name +v.Description);
});
Jsfiddle Demo: http://jsfiddle.net/ashishanexpert/xL7jm/1/
Upvotes: 1
Reputation: 32831
You're enumerating the elements in the list, then the properties of each element. One loop should suffice:
$.each(json, function () {
alert(this.Id + this.Name +this.Description);
});
Upvotes: 1
Reputation: 10638
Maybe you don't need the second loop
$.each(json, function (k, v) {
alert(v.Id + v.Name + v.Description);
});
Upvotes: 4