Reputation: 646
I have a json string that uses golang Template. Is there a way to print the Name
property of {{index .Apps 1}}
? Below is the code I am running. On line 31, I am trying to just print the Name property of 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)
}
Upvotes: 3
Views: 1838