如何从handlebarsjs
访问此json对象 [ {
"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"
} ]
} ]
我已尝试使用{{name}}来访问名称,但这不起作用,那么我如何访问名称属性以及联系人下的嵌套firstName属性?
谢谢
答案 0 :(得分:0)
首先需要索引数组以获取名称。类似的东西:
{{listObj[0].name}}
{{listObj[0].contacts.firstName}}
答案 1 :(得分:0)
将javascript变量名称分配给JSON对象。
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] .name
您可以使用for循环遍历JSON并打印出您需要的信息
for ( var x = 0; x < jsonString.length; x++){
alert(jsonString[x].name);
alert(jsonString[x].contacts.firstName);
}
希望这有帮助
答案 2 :(得分:0)
你很幸运:在Handlebars文档页面上非常清楚地解释了你的问题:
只需向下滚动到“Handlebars Paths”部分,您就会看到它正确地说明了您正在寻找的内容(“Handlebars还支持嵌套路径,因此可以查找嵌套在当前上下文下的属性。 ..“)