sledgeweight
sledgeweight

Reputation: 8105

Getting the correct keys and values to display from JSON file in Jquery

Trying to retrieve specific values in complicated nested JSON arrays is proving tricky. I'm thinking theres another way to do this than what i have below:

 $.getJSON('test.json', function (data) {
    $.each(data.glossary, function (){
     $('ul#results').append('<li><div class=\"name\">' +this.title+ '</div></li><li><div class=\"name\">' +this.GlossTerm+ '</div></li>');
    });
});

Where test.json is:

{
"glossary": {
    "title": "example glossary",
    "GlossDiv": {
        "title": "Hello!!",
        "GlossList": {
            "GlossEntry": {
                "ID": "SGML",
                "SortAs": "SGML",
                "GlossTerm": "Standard Generalized Markup Language",
                "Acronym": "SGML",
                "Abbrev": "ISO 8879:1986",
                "GlossDef": {
                    "para": "A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso": ["GML", "XML"]
                },
                "GlossSee": "markup"
            }
        }
    }
}
}

So far on the web page, the returned results are:

+undefined

+undefined

+Hello!!

+undefined

How would I make the undefined values display the correct value? I've tried numerous methods and none seem to work!

Upvotes: 0

Views: 63

Answers (1)

adeneo
adeneo

Reputation: 318312

You need to traverse the object properly, no way around that ?

$.getJSON('test.json', function (data) {
    $.each(data.glossary, function(index, val){
       var title = val.title, //"example glossary"
           term  = val.GlossDiv.GlossList.GlossEntry.GlossTerm; //"Standard Generalized Markup Language"
    });
});

Upvotes: 2

Related Questions