我有一点疑问!如何从 json 添加到数组数据并执行模板。简单的。但不工作!package mainimport ( "fmt" "html/template" "os" "encoding/json")type Person struct { Name string Jobs []*Job}type Job struct { Employer string Role string}const templ = `The name is {{.Name}}.{{with .Jobs}} {{range .}} An employer is {{.Employer}} and the role is {{.Role}} {{end}}{{end}}`func main() { job1 := Job{Employer: "Monash", Role: "Honorary"} job2 := Job{Employer: "Box Hill", Role: "Head of HE"} byt := []byte(`{"num":6.13,"Jobs":[{"Employer": "test1", "Role": "test1"},{"Employer": "test2", "Role": "test2"}]}`) var dat map[string]interface{} if err := json.Unmarshal(byt, &dat); err != nil { panic(err) } fmt.Println(dat) // HOW ADD FROM ARRAY 'dat' TO STRUCT 'Job' // LINE 54 person := Person{ Name: "jan", Jobs: []*Job{&job1, &job2}, } t := template.New("Person template") t, err := t.Parse(templ) checkError(err) err = t.Execute(os.Stdout, person) checkError(err)}func checkError(err error) { if err != nil { fmt.Println("Fatal error ", err.Error()) os.Exit(1) }}在这里你可以玩/测试代码:http : //play.golang.org/p/AB8hGLrLRy观看第 46 行。非常感谢!
2 回答
- 2 回答
- 0 关注
- 175 浏览
添加回答
举报
0/150
提交
取消