0

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?

6
  • from what i can see in your json you don't need any loops Commented Jul 6, 2016 at 10:10
  • based on your javascript the json shoud look like { "routers" :[ {"os": "4.4.4.4", "name": "DNSROOTSERVER"}]} Commented Jul 6, 2016 at 10:11
  • 1
    try $(data.routers.DNSROOTSERVER).each(...) Commented Jul 6, 2016 at 10:16
  • 1
    @madalinivascu I'll try reformatting the json like you suggested Commented Jul 6, 2016 at 10:21
  • 1
    @madalinivascu you're right, my json was malformed for what i wanted to do with it, if you submit your comment as an answer I'll accept it. Commented Jul 6, 2016 at 10:28

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yep. As you said, my json was malformed. Thanks! Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.