Reputation: 141
in my jquery code, i made ajax request and server returned data in JSON like this:
{"list":{
"category":"book",
"item":[
{"title":"jQuery Cookbook","author":"Tom","publisher":"Wonderland"},
{"title":"PHP Cookbook","author":"Jack London","publisher":"O'Reilly"}
]
}
}
in my jquery code, i have:
$.getJSON(
"data/getFile.php",
{set:setName, list:listName},
function(json) {
var items = json.list.item;
$.each(items, function(key, value) {alert(value);}
});
it turned out value is a object, which is right. my question is how i can parse out both the name and value like : for item 1: key="title", value="jQuery Cookbook"; key="author", value="Tom";...
the reason i need to do this is the item will update dynamically, maybe later user will add more key/value attribute, for example: {"isbn": "11223344"}
Thanks.
Upvotes: 4
Views: 4112
Reputation: 309
u can also use the underscore lib for each key value pair of JSON object
_.each({one : 1, two : 2, three : 3}, function(value, key ){
alert("key : "+ key+" value: "+ value);
});
documentation is on http://underscorejs.org/#each
Upvotes: 0
Reputation: 141
got it, just need to use double loop:
$.getJSON( "data/getFile.php", {set:setName, list:listName}, function(json) { var items = json.list.item; $.each(items, function(i, item) {
$.each(item, function(key, val) {
alert(key + ': ' + val);
});
}
});
Upvotes: 1
Reputation: 630637
You can loop through the items with a for loop like this:
for (var key in items) {
if(items.hasOwnProperty(key)) { //Exclude inherited prototype properties
alert("Key: " + key);
alert("Value: " + items[key]);
}
}
I'm not sure exactly of your destination for the data, but that's the simplest way to grab the key/value for each pair.
Upvotes: 2