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);