2012-07-20 39 views
0

如何从handlebarsjs访问此JSON对象如何访问从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" 
    } ] 
} ] 

我已经试过此JSON对象{{名}}访问的名字,但没有工作,所以我如何访问名称属性和联系人下的嵌套firstName属性?

谢谢

回答

0

您需要先索引到数组中以获取名称。例如:

{{listObj[0].name}} 

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

我一定来跟踪指数的下方,我认为所有我需要做的就是把模板 \t \t \t \t​​{{名}} \t \t \t \t​​{{电话}} \t \t \t \t​​{{传真}} \t \t \t – skystar7 2012-07-20 20:44:30

+0

我得到这个错误:错误:解析错误在第9行: ...> \t \t \t \t \t \t \t​​{{ID [0] .name}} \t \t ---------------------^ 期待'ID',得到'undefined' http:// localhost:8080/LocalApp/scripts/handlebars-1.0。 0.beta.6.js 第194行 – skystar7 2012-07-20 20:48:11

+0

您无法在Handlebars模板中使用[]符号。 – frontendbeauty 2012-08-01 20:08:31

0

为您的JSON对象指定一个javascript变量名称。

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

然后,你可以做jsongstring [0]。名称

您可以通过JSON使用for循环中循环,并打印出您需要的信息

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

希望这帮助

0

您很幸运:您的问题在Handlebars文档页面上有相当清楚的解释:

http://handlebarsjs.com/

只是向下滚动到“手把路径”部分,你会看到它谈论你在寻找什么(“把手也支持嵌套的路径,从而可以查找嵌套的属性目前情况下......“)