4
Answers

Traversing in JSON Data

I have a JSON data as shown below, I want to traverse into it with loop, but data.length is returning 1 while it should return 2.
Please help me out how can I traverse into data with loop without modifying it
 
var data=[{
"468040": {
"Author": "William von Hagen",
"Title": "Ubuntu Linux Bible"
},
"541115": {
"Author": "Lohith G.N.",
"Title": "Windows Phone 7.5 Application Development with F#"
}
}]
alert(data.length);  //returning 1 instead of 2
 
Answers (4)
1
Priyaranjan K S

Priyaranjan K S

NA 35.4k 8.5m 9y
This is the solution I have created . It however uses Jquery . 
https://jsfiddle.net/KSPriyaranjan/unjrpbex/
 
The code uses nested looping . Let me know if this is what you intended to achieve .
 
var data=[{
"468040": {
"Author": "William von Hagen",
"Title": "Ubuntu Linux Bible"
},
"541115": {
"Author": "Lohith G.N.",
"Title": "Windows Phone 7.5 Application Development with F#"
}
}]
$.each(data, function( MainIndex, Mainvalue ) {
$.each(Mainvalue, function( SubIndex, Subvalues ) {
alert( SubIndex + " - " + Subvalues["Author"] );
alert( SubIndex + " - " + Subvalues["Title"] );
});
});

Thanks,
Priyan

Please mark the suggestions as answer if you found it useful.
Accepted
0
Priyaranjan K S

Priyaranjan K S

NA 35.4k 8.5m 9y
Ashish,
Are you in a position to use jquery in the project ?

If so I have worked out a solution .

Thanks,
Priyan 
0
Ashish Vishwakarma

Ashish Vishwakarma

369 4.4k 1.4m 9y
Hi Priyakaran, Thanks for your valuable reply, But I don't want to modify data, because I am getting it from another service and, this is huge as 5 MBs. I need some way to traverse it without modifying JSON
0
Priyaranjan K S

Priyaranjan K S

NA 35.4k 8.5m 9y
Hi Ashish ,
 
Ideally the JSON return array value should look like below :
var data=[
{"ID":"468040",
"Author": "William von Hagen",
"Title": "Ubuntu Linux Bible"
},
{
"ID":"541115",
"Author": "Lohith G.N.",
"Title": "Windows Phone 7.5 Application Development with F#"
}
];
alert(data.length);
for(var i = 0; i < data.length; i++) {
alert(data[i].Author);
}
 
Try to get the array value in this format and the looping should work .
I have created a jsfiddle here with the above array format: https://jsfiddle.net/KSPriyaranjan/kjn40jdf/