Reputation: 157
I am having the most difficult time parsing the json below using jquery.
{ "client": [{"ClientID": "0000000001", "Name": "Valdez Gilberto JR", "Phone": "(956)542-8148" , "MedActID": "10", "Gender": "M", "Division": "WP", "Address": "1905 Illinois Ave N", "Class": "", "CityState": "Brownsville TX 78521-6732" } , {"ClientID": "0000000002", "Name": "Salazar Olga F", "Phone": "(956)546-3909" , "MedActID": "100", "Gender": "F", "Division": "MP", "Address": "Route 8 Box 626 (San Pedro)", "Class": "", "CityState": "Brownsville TX 78520" } ]}
Been using the code below but to no avail, keep getting undefined errors "data" is being called via ajax:
var obj = JSON.parse(data);
for(var i = 0; i < obj.length; i++){
alert(obj[i].client.Name)
}
Have even tried the following:
$.each(obj, function(key,value) {
alert(value.client.Name);
});
Upvotes: 2
Views: 6148
Reputation: 7184
You should grab the "client" property first which is an array. Once you grab it, then you can iterate over it as an array.
{ //object | obj
"client":[ //property (array) | obj.client
{ //object inside array | obj.client[0]
"ClientID":"0000000001",
"Name":"Valdez Gilberto JR", //property | obj.client[0].Name
"Phone":"(956)542-8148",
"MedActID":"10",
"Gender":"M",
"Division":"WP",
"Address":"1905 Illinois Ave N",
"Class":"",
"CityState":"Brownsville TX 78521-6732"
},
{
"ClientID":"0000000002",
"Name":"Salazar Olga F",
"Phone":"(956)546-3909",
"MedActID":"100",
"Gender":"F",
"Division":"MP",
"Address":"Route 8 Box 626 (San Pedro)",
"Class":"",
"CityState":"Brownsville TX 78520"
}
]
}
This code will iterate over the objects inside the "client" property, and alert the names.
var obj = JSON.parse(data);
var client = obj.client; //client prop is an array
for(var i = 0; i < client.length; i++){
alert(client[i].Name);
}
Upvotes: 3
Reputation: 6145
You are trying to iterate through an object. obj.client
is the Array you are looking for.
var data = '{ "client": [{"ClientID": "0000000001", "Name": "Valdez Gilberto JR", "Phone": "(956)542-8148" , "MedActID": "10", "Gender": "M", "Division": "WP", "Address": "1905 Illinois Ave N", "Class": "", "CityState": "Brownsville TX 78521-6732" } , {"ClientID": "0000000002", "Name": "Salazar Olga F", "Phone": "(956)546-3909" , "MedActID": "100", "Gender": "F", "Division": "MP", "Address": "Route 8 Box 626 (San Pedro)", "Class": "", "CityState": "Brownsville TX 78520" } ]}';
var obj = JSON.parse(data);
for (var i = 0; i < obj.client.length; i++) {
console.log(obj.client[i].Name);
}
Upvotes: 0
Reputation: 73291
You are trying to iterate an object, but you can't do that. What you want is to iterate trough the array which is in your object, keyed by client
Try this:
for(var i = 0; i < obj.client.length; i++){
console.log(obj.client[i].Name)
}
Upvotes: 0