4

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

           });  

        }
    });

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.