Keef Baker Keef Baker - 5 months ago 18
JSON Question

How to loop over elements in a json list Ajax/Javascript

I have an issue where ajax can see the data I've given it from flask, but it doesn't seem to be parsing inside when I loop it. This is currently a 1 item loop, but it will be more when data is fed into it.

Json string is:

{ "routers" : {"DNSROOTSERVER": {"os": "4.4.4.4", "name": "DNSROOTSERVER"}}}


so it understands data.routers, and it even understands data.routers.DNSROOTSERVER.name (as you'll see in the console.log), but when I use a loop over data.routers, the looped item displays (el), but it seems to fail when i try el.name, saying it's undefined. Javascript is below:

$(document).ready(function(){
$.ajax({ url: "{{ url_for('.gui_form') }}", dataType: 'json',
success: function(data, textStatus, xhr){
console.log(data)
$(data.routers).each(function(i, el) {
console.log(el)
console.log(el.os)
console.log(data.routers.DNSROOTSERVER.os)
var listem = "<br>" + el.name;
$("#routers").append("<li>" + listem + "</li>");
});
}
});
});


I've expanded the console log so you can see the data is there and how the looped el.os comes out undefined but data.routers.DNSROOTSERVER.name comes out cleanly as ios:

Object {routers: Object}routers: ObjectDNSROOTSERVER: Objectip: "4.4.4.4"name: "DNSROOTSERVER"os: "ios"__proto__: Object__proto__: Object__proto__: Object
Object {DNSROOTSERVER: Object}DNSROOTSERVER: Objectip: "4.4.4.4"name: "DNSROOTSERVER"os: "ios"__proto__: Object__proto__: Object
undefined
ios


Any ideas what I'm doing wrong?

Answer

Based on your javascript the json shoud look like { "routers" :[ {"os": "4.4.4.4", "name": "DNSROOTSERVER"}]}