March 29, 2012

Accessing lower level data in JSON

Question by SeasonEnds

I’ve done some searching, but I’ve been unable to fully understand how this is done. I am relatively new to jQuery and JSON. Basically, I have a massive JSON document that I am connecting to and displaying various data from it. The data I need is the Supplier Label, which is nested three levels down, and I’m unsure how to return it.

The JSON

    {
    "@order": "1",
    "category": {
        "@id": "204",
        "label": "Category 1",
        "suppliers": {
            "supplier": {
                "label": "Business 1",
                "customicons": [
                    {
                        "@id": "images/img2.jpeg",
                        "#text": "random icon"
                    }
                ]
            }
         }
       }
    },

Here’s the script that I’ve made to form an unordered list. I tried item.category.suppliers.supplier.label, which obviously isn’t working. Do I need to add some function that iterates through each sub level? How do I get to that label?

    <script type="text/javascript">
$(document).ready(function(){

    $.getJSON('jsonarray.json', 
    function(data) {

      var items = [];

      $.each(data, function(i,item) {

        items.push('<li id="' + item["@order"] + '"><label for="supplier"><input id="supplier" name="supplier" type="checkbox" class="checkbox"/>' + item.category.suppliers.supplier.label + '</label></li>');

      });

      $('<ul/>', {
        'class': 'checklist-supplier cl2',
        html: items.join('')
      }).appendTo('.list_filter_supplier_side');
    });

});
</script>

So, basically the question is how do I access sub level data in JSON using jQuery? Any clarification is greatly appreciated.

Answer by MattW

is the JSON in some sort of response? If so you can do something like this:

var d = {
"@order": "1",
"category": {
    "@id": "204",
    "label": "Category 1",
    "suppliers": {
        "supplier": {
            "label": "Business 1",
            "customicons": [
                {
                    "@id": "images/img2.jpeg",
                    "#text": "random icon"
                }
            ]
        }
     }
   }
}

//just show the label    
alert(d.category.suppliers.supplier.label);

jsFiddle Example

Answer by Starx

Except that, You are using the correct way of accessing the data

item.category.suppliers.supplier.label

Validate your JSON using jsonlint to confirm its validation

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!