Using Anonymous Structs in Go 02-08-2017, 05:15 PM
#1
This is just a short tutorial about using anonymous structs in Go, which can be very handy when dealing with JSON server responses (especially from Facebook).
So say you have this JSON response from the server:
and you want to put `lights` into a Go struct that looks like this:
with anonymous structs you can now do this with ease!
Here is a link to a Go playground where I implemented this example.
Good luck with your Go coding!
So say you have this JSON response from the server:
Code:
{
"lights" : {
{"livingroomLight" : true},
{"bathroomLight" : false},
{"kitchenLight" : false}
}
}
and you want to put `lights` into a Go struct that looks like this:
Code:
type Lights struct {
Toggles map[string]bool
}
with anonymous structs you can now do this with ease!
Code:
type Lights struct {
Toggles map[string]bool
}
var lights Lights
if err := json.Unmarshal("json_data", &struct{
Temp *map[string]bool `json:"lights"`
}{
Temp: &lights.Toggles,
}); err != nil {
// TODO: handle error
}
Here is a link to a Go playground where I implemented this example.
Good luck with your Go coding!
(This post was last modified: 02-09-2017, 07:59 AM by Hoss.)
this forum is dead