Reputation: 690
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?
Upvotes: 0
Views: 3737
Reputation: 79830
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]);
}
}
}
Upvotes: 1
Reputation: 69905
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;
Upvotes: 2
Reputation: 754575
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);
Upvotes: 0
Reputation: 342635
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/
Upvotes: 0