I have a little qiestion!
How add to array data from json and execute template. Simple. But Not working!
package main
import (
"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)
}
}
Here you can play/test code: http://play.golang.org/p/AB8hGLrLRy
Watch line 46.
Thank you very much!
First thing, your dat
var isn't of the right type. You should have something like that:
dat := struct {
Jobs []*Job
}
That way, when unmarshalling your JSON string into dat
, the Jobs
key will be filled with a array of *Job
initialized with your data's array. I'm using an anonymous struct, but you could also have a named struct (see @RoninDev's comment for an example).
Then, just add them to the person array, something like that:
person.Jobs = append(person.Jobs, jobs.Jobs...)
Note the ...
operator, which use an array as a variadic argument.
You can see the full working code on this playground.
You're unmarshalling the json fine, it's just into the most ambiguous type the language offers... You could unbox it with a series of type asserts but I don't recommend it. The json can easily be modeled in Go with a structure like the following;
type Wrapper struct {
Num float64 `json:"num"`
Jobs []*Job `json:"Jobs"`
}
Here's an updated example of your code using that struct; http://play.golang.org/p/aNLK_Uk2km
After you've deserialized them you can just use append
to add them to the jobs array in the person object like person.Jobs = append(person.Jobs, dat.Jobs...)