aminjam
aminjam

Reputation: 646

Golang Template property of struct in Index

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

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65049

You can wrap it in parenthesis:

{{(index .Apps 1).Name}}

Playground link

Upvotes: 7

Related Questions