How to extract string key and value from json object

in my jquery code, I made an ajax request and the server returned the data in JSON as follows:

{"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 that value is an object that is correct. my question is how can I parse both the name and value as: for element 1: key = "title", value = "jQuery Cookbook"; key = "author", value = "Tom"; ...

the reason I need to do this is to update the element dynamically, maybe later the user will add more key / value attribute, for example: {"isbn": "11223344"}

Thanks.

+4
source share
3 answers

You can scroll through elements with a for loop as follows:

 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 about your purpose for the data, but this is the easiest way to capture the key / value for each pair.

+2
source

got it, just need to use a 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); }); } }); 
+1
source

u can also use an underscore for each key value pair of a JSON object

 _.each({one : 1, two : 2, three : 3}, function(value, key ){ alert("key : "+ key+" value: "+ value); }); 

the documentation is at http://underscorejs.org/#each

0
source

Source: https://habr.com/ru/post/1303859/


All Articles