How to access this json object from handlebarsjs

╄→尐↘猪︶ㄣ 提交于 2019-12-04 05:51:22

问题


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 ...")



来源:https://stackoverflow.com/questions/11586459/how-to-access-this-json-object-from-handlebarsjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!