Katie
Katie

Reputation: 751

Navigating through a JSON API tree using jQuery

I'm trying to use a JSON api and retrieve some data. I'm still new to it though and I can't seem to figure out which value to use. My JSON API looks something like this:

[
   {"lang":"english","visual":"<span>Text</span>","weight":0.92},
   {"lang":"swedish","visual":"<span>Text</span>","weight":0.22},
   //etc
]

and my jQuery is:

     $.getJSON(url ,function(data) {
            $.each(data.lang, function(i, item) {
                dataName = item["visual"];
                        console.log(dataName);
            });
        });

but nothing is being logged. How do I navigate through a JSON tree? Thanks

Upvotes: 1

Views: 183

Answers (1)

Travis J
Travis J

Reputation: 82287

data.lang is undefined. lang is a property of each object in the array of objects that data holds. Simply iterate the data array, each object will contain the visual property (as well as lang);

$.getJSON(url ,function(data) {
    $.each(data, function() {
        var lang = this["lang"];
        var dataName = this["visual"];
        console.log(dataName);
    });
});

Upvotes: 1

Related Questions