I can't figure out how I can serialize the same JSON object with a different key to Go slice struct without re-writing entire parser. For example, JSON that I can receive back, it might contain N number object with a different key (localhost1/localhost2/localhost3, etc). In this example, I have a key localhost1/localhost2/localhost3, and each has only one field ok.
{
"stats": {
"localhost1": {
"ok": 1
},
"localhost2": {
"ok": 1
},
"localhost3": {
"ok": 1
}
}
}
I can Unmarsh entire JSON by using the following Structs mappings.
type HostStatus struct {
Ok int `json:"ok"`
}
type Test struct {
Stats struct {
Localhost1 HostStatus `json:"localhost1"`
Localhost2 HostStatus `json:"localhost2"`
Localhost3 HostStatus `json:"localhost3"`
} `json:"stats"`
}
Entire Example.
package main
import (
"encoding/json"
"fmt"
)
type HostStatus struct {
Ok int `json:"ok"`
}
type Test struct {
Stats struct {
Localhost1 HostStatus `json:"localhost1"`
Localhost2 HostStatus `json:"localhost2"`
Localhost3 HostStatus `json:"localhost3"`
} `json:"stats"`
}
func main() {
var resp = []byte(`{
"stats": {
"localhost1": {
"ok": 1
},
"localhost2": {
"ok": 1
},
"localhost3": {
"ok": 1
}
}
}`)
var r Test
er := json.Unmarshal(resp, &r)
if er != nil {
panic(er)
} else {
fmt.Println(r)
}
}
The main issue in this solution that it requires hardcode inside a Stats struct each HostStatus that maps 1:1 to JSON output via json:xxx tag. But I want to find a way to map all this object to a HostStatus slice/array since I don't know how many HostStatus objects I might receive back and what is the key for each.
For example something like
type Test struct {
Stats struct {
LocalHostList []HostStatus `json:"localhost[0-9]"`
} `json:"stats"`
}
and use something like localhost[0-9] -- i.e regex semantics that will give a hit to JSON package.