Suppose I have a Go struct, complete with JSON tags:
type Person struct {
Name string `json:"name"`
Age int `json:"age,omitifempty"`
Flags []string `json:"-"`
}
p := Person{ Name: "Bob", Age: 36, Flags: []string{"employed","father"} }
Now I want to convert this to a generic map[string]interface{}
, such as I might receive from a REST API via JSON:
p2 := map[string]interface{}{
"name": "Bob",
"age": 36,
}
I have devised the following function to accomplish this using the json package. But the intermediate step of a JSON string seems unnecessary and wasteful.
func ConvertJSONObject(input, output interface{}) error {
encoded, err := json.Marshal(input)
if err != nil {
return err
}
return json.Unmarshal(encoded, output)
}
Now I can do this:
var p2 map[string]interface{}
ConvertJSONObject(p, &p2)
As an added bonus, the same function works in reverse, to turn a map[string]interface{}
into a populated struct:
var p Person
ConvertJSONObject(p2, &p)
Is there a simpler solution, which honors tags in the roughly the same way the json package does?