I have some JSON code that can look like:
{
"message_id": "12345",
"status_type": "ERROR",
"status": {
"x-value": "foo1234",
"y-value": "bar4321"
}
}
or can look like this. As you can see the "status" element changes from a standard object of strings to an object of array of strings, based on the status_type.
{
"message_id": "12345",
"status_type": "VALID",
"status": {
"site-value": [
"site1",
"site2"
]
}
}
I am thinking that I need to have my struct for "Status" take a map like "map[string]interface{}", but I am not sure exactly how to do that.
You can see the code here on the playground as well.
http://play.golang.org/p/wKowJu_lng
package main
import (
"encoding/json"
"fmt"
)
type StatusType struct {
Id string `json:"message_id,omitempty"`
Status map[string]string `json:"status,omitempty"`
}
func main() {
var s StatusType
s.Id = "12345"
m := make(map[string]string)
s.Status = m
s.Status["x-value"] = "foo1234"
s.Status["y-value"] = "bar4321"
var data []byte
data, _ = json.MarshalIndent(s, "", " ")
fmt.Println(string(data))
}
I figured it out, I think..
package main
import (
"encoding/json"
"fmt"
)
type StatusType struct {
Id string `json:"message_id,omitempty"`
Status map[string]interface{} `json:"status,omitempty"`
}
func main() {
var s StatusType
s.Id = "12345"
m := make(map[string]interface{})
s.Status = m
// Now this works
// s.Status["x-value"] = "foo1234"
// s.Status["y-value"] = "bar4321"
// And this works
sites := []string{"a", "b", "c", "d"}
s.Status["site-value"] = sites
var data []byte
data, _ = json.MarshalIndent(s, "", " ")
fmt.Println(string(data))
}
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