tags:

views:

256

answers:

2

hi,

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.

+2  A: 

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.

Nick Craver
+1  A: 

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

           });  

        }
    });
Ohana