[RESOLVED]Jquery and JSON incorrect Display

Hello,

I have the following JSON file

1.{
"subject": "title",
"level": [
 {
  "title":"Test1",
  "sub":[{
   "title":"Test1 sub_1",
   
   "links":[{
    "title":"Test1sub1.1link_title",
    "address":"linkAddress"
    },{
    "title":"Test1sub1.2_link_title",
    "address":"linkAddress"
    }
   ] 
  
  },{
   "title":"Test2 sub_2",
   
   "links":[{
    "title":"Test2sub2.1_link_title",
    "address":"linkAddress"
    },{
    "title":"Test2sub2.2_link_title",
    "address":"linkAddress"
    }
   ]
  }]  
 },
 {
  "title":"Test3",
  "sub":[{
   "title":"Test3 sub_1",
   
   "links":[{
    "title":"Test31.1_link_title",
    "address":"linkAddress"
    },{
    "title":"Test31.2_link_title",
    "address":"linkAddress"
    }
   ] 
  
  }]
 }
 
 ]
}

In my markup I have the following

1.var json = $.getJSON('datar.json',function(data){
 for(var i =0; i< data.level.length; i++){
   
   console.log(data.level[i].title);
   $('#accordion').append("<li>"+data.level[i].title+"</li>");
  
   for (var k = 0; k<data.level[i].sub.length; k++){
    
    console.log(data.level[i].sub[k].title);
    $('#accordion').append("<li>"+data.level[i].sub[k].title+"</li>");
    for (var j = 0; j<data.level[i].sub[k].links.length; j++){
    
     console.log(data.level[i].sub[k].links[j].title);
     $('#accordion').append("<li>"+data.level[0].sub[j].links[i].title+"</li>");
  
    }
   }
  } 

As we can see I’m looping through and appending to create dynamic lists based on parent and there children. From my console.log output I receive the correct format I require.

1.Test1 
Test1 sub_1 
Test1sub1.1link_title
Test1sub1.2_link_title
Test2 sub_2 
Test2sub2.1_link_title 
Test2sub2.2_link_title
Test3
Test3 sub_1 
Test31.1_link_title 
Test31.2_link_title 

But on the HTML page its incorrect format,

Test1
Test1 sub_1
Test1sub1.1link_title
Test2sub2.1_link_title
Test2 sub_2
Test1sub1.1link_title
Test2sub2.1_link_title
Test3
Test3 sub_1
Test1sub1.2_link_title
Test2sub2.2_link_title

I thinks its in the following loop,

for (var j = 0; j<data.level[i].sub[k].links.length; j++){
    
     console.log(data.level[i].sub[k].links[j].title);
     $('#accordion').append("<li>"+data.level[0].sub[j].links[i].title+"</li>");
  
    }

If anyone could advise it will be greatly appreciated.

Regards, Richard

In last append statement, use this

$('#accordion').append("<li>"+data.level[i].sub[k].links[j].title+"</li>");

Leave a Reply