我有一个使用 golang 模板的 json 字符串。有没有办法打印的Name
属性{{index .Apps 1}}
?下面是我正在运行的代码。在第 31 行,我试图只打印Apps[0]
.
http://play.golang.org/p/4RNevdqxP1
package main
import (
"encoding/json"
"os"
"text/template"
)
type Message struct {
Name string
Id int
Apps []App
Company Company
}
type App struct {
Name string `json:"name"`
Device string `json:"device"`
}
type Company struct {
UserId string
}
func main() {
msg := []byte(`{
"Name":"Bob",
"Id":1,
"apps":[{"name":"app1","device":"ios"},{"name":"app2","device":"android"}, {"name":"app3","device":"ios"}],
"company":
{
"userId":"{{.Name}}-{{.Id}}",
"app":["{{index .Apps 0}}","{{index .Apps 1}}"]
}
}`)
var m Message
json.Unmarshal(msg, &m)
t := template.New("My template")
t, _ = t.Parse(string(msg))
t.Execute(os.Stdout, m)
}