How to access this json object from handlebarsjs

2019-03-04 09:43发布

问题:

How to access this json object from handlebarsjs

    [ {
    "id" : 9,
    "name" : "Name1",
    "address" : "address1",
    "city" : "city1",
    "state" : "KS",
    "zip" : "11111",
    "country" : "USA",
    "fax" : "111111",
    "phone" : "1111111",
    "website" : "",
    "account" : "11111",
    "contacts" : []
}, {
    "id" : 12,
    "name" : "Name2",
    "address" : "address2",
    "city" : "city2",
    "state" : "NJ",
    "zip" : "11111",
    "country" : "USA",
    "fax" : "",
    "phone" : "1111",
    "website" : "",
    "account" : "11111",
    "contacts" : [ {
        "firstName" : "name",
        "lastName" : "lastname",
        "title" : "rep",
        "phone" : "3333",
        "email" : "33333"
    } ]
} ]

I have tried {{name}} to access name but that didn't work, so how do i access name attribute, and the nested firstName attribute under contacts?

Thank you

回答1:

You need to index into the array first in order to get the name. Something like:

{{listObj[0].name}}

{{listObj[0].contacts.firstName}}


回答2:

Assign a javascript variable name to your JSON object.

   var jsonstring = [ {
        "id" : 9,
        "name" : "Name1",
        "address" : "address1",
        "city" : "city1",
        "state" : "KS",
        "zip" : "11111",
        "country" : "USA",
        "fax" : "111111",
        "phone" : "1111111",
        "website" : "",
        "account" : "11111",
        "contacts" : []
    }]

Then you can do jsongstring[0].name

You can use a for loop to loop over the JSON and print out the information you need

for ( var x = 0; x < jsonString.length; x++){
alert(jsonString[x].name);
alert(jsonString[x].contacts.firstName);
}

Hope this helps



回答3:

You're in luck: your question is explained pretty clearly on the Handlebars documentation page:

http://handlebarsjs.com/

Just scroll down to the "Handlebars Paths" section, and you'll see it talks about exactly what you're looking for ("Handlebars also supports nested paths, making it possible to look up properties nested below the current context ...")