I’m trying to convert JSON to a generic struct in Go, where the struct can have fields with varied types. To handle different types of data, I’m using the interface{} type in the struct fields. However, I don’t know the exact structure of the JSON object that will be unmarshalled, so I need a flexible solution. When I unmarshal the JSON, I end up with a map[string]interface{}, but I want to get an object (struct).
For example, given this JSON:
{
"animal": "Elephant",
"age": 15,
"location": {
"country": "Kenya",
"continent": "Africa"
},
"diet": ["grass", "fruit", "vegetables"]
}
Here is the Go code I am using:
package main
import (
"encoding/json"
"fmt"
)
type GenericStruct struct {
Animal interface{} `json:"animal"`
Age interface{} `json:"age"`
Location interface{} `json:"location"`
Diet interface{} `json:"diet"`
}
func main() {
jsonData := `{
"animal": "Elephant",
"age": 15,
"location": {
"country": "Kenya",
"continent": "Africa"
},
"diet": ["grass", "fruit", "vegetables"]
}`
var result GenericStruct
err := json.Unmarshal([]byte(jsonData), &result)
if err != nil {
fmt.Println("Error:", err)
}
fmt.Printf("Result: %+vn", result)
}
Instead of getting a map[string]interface{}, I want to directly unmarshal into a struct with interface{} fields, so that I can handle the varied types more easily.
Current output:
map[age:15 animal:Elephant diet:[grass fruit vegetables] location:map[continent:Africa country:Kenya]]
Desired output (as an object):
{Animal:Elephant Age:15 Location:{Country:Kenya Continent:Africa} Diet:[grass fruit vegetables]}
I tried using mapstructure.Decode(data, &result) but it didn’t work either.
How can I achieve this in Go? Am I missing some Go concept to make this work correctly?