I'm new to Go and am trying to decode a json blob via feeding structs to Unmarshal. Trouble is, I dont know certain keys. I can parse the following
{"age":21,"Travel":{"fast":"yes","sick":false} }
like so
type user struct {
Age int
Travel TravelType
}
type TravelType struct {
Fast string
Sick bool
}
func main() {
src_json := []byte(`{"age":21,"travel":{"fast":"yes","sick":false}}`)
u := user{}
err := json.Unmarshal(src_json, &u)
if err != nil {
panic(err)
}
fmt.Printf("%v", u)
}
to obtain {21 {yes false}}
However, I dont see how I would approach something like this-
{
"age":21,
"Travel":
{
"canada":
{"fast":"yes","sick":false},
"bermuda":
{"fast":"yes","sick":false},
"another unknown key name":
{"fast":"yes","sick":false},
}
}
without explictly declaring "Canada", "Bermuda", etc in structs. How could I use Unmarshal to parse the above json? I found this answer, but dont see how it might be implemented
You can Unmarshal into a map[string]TravelType
. Change your user
struct to this and you should be good to go:
type user struct {
Age int
Travel map[string]TravelType
}
Here's a working proof-of-concept on the Go Playground: http://play.golang.org/p/-4k9GE5ZlS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With