简体   繁体   中英

Iterate JSON Response in Jquery

Am new to jquery. Have json response from php in this format.

{
"div1":{"data":"minute=0,hour=27,day=649,month=19K,smallSize=0, id=XXXXXXXXXX, ip=yyyyyyyyyyy<br \/>\nminute=0,hour=34,day=825,month=24K,smallSize=0, id=XXXXXXXXXX, ip=yyyyyyyyyyy<br \/>\nminute=0,hour=40,day=980,month=29K,smallSize=0, id=XXXXXXXXXX, ip=yyyyyyyyyyy<br \/>\n","address":"232323"},
"div2":{"data":"","address":"232323"},
"div3":{"data":"minute=0,hour=28,day=682,month=20K,smallSize=0, id=XXXXXXXXXX, ip=yyyyyyyyyyy<br \/>\nminute=0,hour=36,day=866,month=26K,smallSize=0, id=XXXXXXXXXX, ip=yyyyyyyyyyy<br \/>\nminute=0,hour=42,day=1019,month=30K,smallSize=0, id=XXXXXXXXXX, ip=yyyyyyyyyyy<br \/>\n","address":"232323"}
}

How i need to iterate this JSON in jquery and fetch the div1>data and div1>address,div2>data and div2>address. can anyone help me?

Try this using jQuery each method.

var obj = {  ... };

$.each(obj, function(key, value) {
    //key - each object in the json object
    //value - its value
});

If it is a well formed json string and not an object then you need to first parse it using parseJSON method and then use it to iterate through it.

   var obj = $.parseJSON(jsonString);

Then you can directly access the required properties as below

div1>data => obj.div1.data;

div1>address => obj.div1.address;

div2>data => obj.div2.data;

div2>address => bj.div2.address;

Edit: jQuery version of the same here DEMO

function viewJSON (jsonObj) {
   var divData;
   $.each (jsonObj, function (key, value) {
     divData = value; //gives me the value of div 1

     $. each (value, function (key, value) {
         console.log ('Key is ' + key + ' Value is ' + value);
     });

   });   
}

you can also use simple javascript iterate to get div1>data, (non-jQuery version)

   function viewJSON (jsonObj) {
   var divData;
   for (divKey in jsonObj) {
     divData = jsonObj [divKey]; //gives me the value of div 1

       for (dataKey in divData) {
         console.log ('Key is ' + dataKey + ' Value is ' + divData[dataKey]);
       }

     }    
   }

DEMO HERE

Loop or directly access?

$.each(json, function(key, val) {
    console.log(key + ' ' + val.data + ' ' + val.address);
});

Direct access:

console.log(json.div1.data);
console.log(json.div1.address);
// etc

http://jsfiddle.net/karim79/CKDXU/

The easiest way is to simply parse the JSON and talk directly to the resulting object.

var theResponse = ...;
var obj = $.parseJSON(theResponse);
console.log(obj.div1.data);
console.log(obj.div1.address);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM