I'm trying to place a json array into a struct from Google Analytics API.
EG:
"rows": [
[
"female",
"18-24",
"1308"
],
[
"female",
"25-34",
"741"
]
]
Typically I'd have key/value so I can put json:"gender"
but there are no keys to associate with, so the values that it would search for change.
The struct would be:
type Row struct {
Gender string `json:"gender"`
AgeRange string `json:"blah"`
Count string `json:"blah"`
}
If I do len(jResp.Rows) I can see that it's grabbing all twelve rows/arrays but the fields are empty.
I don't think it's possible, with encoding/json
to directly decode that json into a slice of structs without first implementing a UnmarshalJSON
method on your Row
type.
func (r *Row) UnmarshalJSON(data []byte) error {
var s []string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if len(s) >= 3 {
r.Gender = s[0]
r.AgeRange = s[1]
r.Count = s[2]
}
return nil
}
// make sure it's a slice of pointers to Row
type Resp struct {
Rows []*Row `json:"rows"`
}
Edit: fixed the code a little to make it actually compile. Heres a working example https://play.golang.org/p/eqVQj65xJv.
You could also just decode the data first into a slice of strings and then loop over the result to build you struct values.
type Resp struct {
Rows [][]string `json:"rows"`
}
type Row struct {
Gender string `json:"gender"`
AgeRange string `json:"blah"`
Count string `json:"blah"`
}
var resp jResp
if err := json.Unmarshal(data, &resp); err != nil {
panic(err)
}
var rows = make([]Row, len(resp.Rows))
for i, r := range resp.Rows {
rows[i] = Row{
Gender: r[0],
AgeRange: r[1],
Count: r[2],
}
}
Edit: fixed this one as well. https://play.golang.org/p/Otb7iULSh3