I'm having a heck of a time figuring out how to unmarshal a large unstructured json response into a usable object.
Here is a sample response (trimmed to show the part I'm having trouble with)
This has been greatly trimmed as this is a very large json response. I left the struct tags off below as well for simplicity.
{
"responseStatus": "ok",
"responseHeader": {
"status": "ok",
"requestId": "blah"
},
"responseData": {
"records": [
{
"name": "blah",
"site": {
"id": 1,
"name": "west"
},
"somevar1": "someval",
"somevar2": {
"x": 2,
"y": 1
},
"entries": [
{
"model": "100",
},
{
"model": "200",
}
]
},
]
}
So records is a large list of "objects". I need to convert these to a type I defined. The "entries" list also needs to be converted to its object type.
type Record struct {
Name string
Site map[string]string
Somevar1 string
Somevar2 map[string]string
Entries []Entry
}
type Entry struct {
Model string
}
Here I can get the responseData into an object I can iterate over:
results := data["responseData"].(map[string]interface{})
devices := results["records"].([]interface{})
for _, device := range devices {
fmt.Fprintf(os.Stdout, "%T
", device)
fmt.Fprintf(os.Stdout, "%+v
", device)
}
Here is a sample output from 1 iteration:
map[string]interface {}
map[name:foo site:map[id:2 name:somewhere somevar1: blah somevar2:map[x:1 y:2] entries:[map[model:100] map[model:200]
This is where I'm stuck. I need to take this line above and get convert it into my type Record while also converting the Entries to []Entry.
Change the Site
and Somevar2
fields to map[string]interface{}
or to a proper struct, because their corresponding json contains ints, so when you use only map[string]string
it will fail.
Other than that your code works https://play.golang.com/p/rTgaXhXD1V6