Drum Drum - 4 months ago 31
Jade Question

Addressing Objects in a JSON Array

I'm sending a JSON array to a script for further processing. The JSON array contains a bunch of objects each of which contain a further array of objects. What I need to know is how to access values within those nested objects. So, for instance, if the script receives the following:

petlist = [
{"cats":[
{"catName":"Felix","catType":"British short haired"}
]
},
{"dogs":[
{"dogName":"Fido","dogType":"Labrador"}
]
},
{"fish":[
{"fishName":"Bob","fishType":"Goldfish"}
]
},
{"birds":[
{"birdName":"Polly","birdType":"Parrot"}
]
}
]


How would I then address, say, a) dogName, b) birdType, or c) the entire cats object?

Also, am I correct in my terminology here? As I understand it the stuff in square brackets is an array, while the stuff in curly braces is an object.

edit: I am building the JSON in Javascript and I then need to access the elements in a Jade template (in an 'each' loop)

Thanks

Answer

I changed your JSON a little bit because I think it was not very fun to work with. Basically I just loop through the objects thats why I thought you should have a key like name instead of dogName, catName and so on.

You can find the working example with Jade in this JSFiddle

HTML

<div id="jadeoutput"></div>
<pre id="jadeinput" style="display:none">
- console.log(petlist)
h1 List
  ul.list
    - for(var i in petlist)
      li= "Item - "+ petlist[i].name 
      - for(var j in petlist[i].pets)
      li= "Pet - " + petlist[i].pets[j].name + " " + petlist[i].pets[j].type
</pre>

JavaScript

$(function() {
    var json = {
    "petlist" : [
        { 
            "name" : "cats",
            "pets":
            [
                { "name":"Felix","type":"British short haired"}
            ]
        },
        {
            "name" : "dogs",
            "pets":
            [
                {"name":"Fido","type":"Labrador"}
            ]
        },
        {
            "name" : "fish",
            "pets":
            [
                {"name":"Bob","type":"Goldfish"}
            ]
        },
        {
            "name" : "birds",
            "pets" :
            [
                {"name":"Polly","type":"Parrot"}
            ]
        }
    ]};

    $("#jadeoutput").html(jade.compile($("#jadeinput").html())(json));
});