Keef Baker Keef Baker - 1 year ago 75
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": "", "name": "DNSROOTSERVER"}}}

so it understands data.routers, and it even understands (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, saying it's undefined. Javascript is below:

$.ajax({ url: "{{ url_for('.gui_form') }}", dataType: 'json',
success: function(data, textStatus, xhr){
$(data.routers).each(function(i, el) {
var listem = "<br>" +;
$("#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 comes out cleanly as ios:

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

Any ideas what I'm doing wrong?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download