There is an easy way to create a value of some data structure where you know the JSON output you want to generate/duplicate:
Take the output you want to generate, and unmarshal it into a map[string]interface{}
. You will get a map value which when you marshal will result in your desired output. When you unmarshal an expected output, you can inspect the result map value to know what you need to create in order for your expected output.
This works in your case too. Here is the code:
var m map[string]interface{}
err := json.Unmarshal([]byte(input), &m)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", m)
res, err := json.MarshalIndent(m, "", " ")
if err != nil {
panic(err)
}
fmt.Println(string(res))
Where input
is your JSON input:
const input = `{
"item": [
{
"value": "274057"
},
[
"38594",
"39957",
"35316",
"35913",
"36668",
"45660",
"41949"
]
]
}`
This program generates the same output as your required output (or input):
map[item:[map[value:274057] [38594 39957 35316 35913 36668 45660 41949]]]
{
"item": [
{
"value": "274057"
},
[
"38594",
"39957",
"35316",
"35913",
"36668",
"45660",
"41949"
]
]
}
Try the complete application on the Go Playground.
Analyzing your unmarshaled map value:
Obviously it has a key "item"
, its value's type:
fmt.Printf("%T\n", m["item"]); // Prints []interface{}
So it's a slice. It has 2 values, their types:
fmt.Printf("%T\n", m["item"].([]interface{})[0]); // map[string]interface{}
fmt.Printf("%T\n", m["item"].([]interface{})[1]); // []interface{}
So the slice contains 2 values:
- a map (the
"value" : "274057"
pair)
- and another slice (the list of ids or numbers)
Here is the Go code to reproduce the same map value:
m := map[string]interface{}{
"item": []interface{}{
map[string]interface{}{"value": "274057"},
[]interface{}{"38594", "39957", "35316", "35913", "36668", "45660", "41949"},
},
}
Marshaling this produces the same JSON output.