Use nested structures in Go to map nested structures in JSON.
Here is an example of how to handle your JSON example:
package main import ( "encoding/json" "fmt" "log" ) func main() { jStr := ` { "AAA": { "assdfdff": ["asdf"], "fdsfa": ["1231", "123"] } } ` type Inner struct { Key2 []string `json:"assdfdff"` Key3 []string `json:"fdsfa"` } type Container struct { Key Inner `json:"AAA"` } var cont Container if err := json.Unmarshal([]byte(jStr), &cont); err != nil { log.Fatal(err) } fmt.Printf("%+v\n", cont) }
link to playgrounds
You can also use an anonymous type for the internal structure:
type Container struct { Key struct { Key2 []string `json:"assdfdff"` Key3 []string `json:"fdsfa"` } `json:"AAA"` }
link to playgrounds
or both external and internal structures:
var cont struct { Key struct { Key2 []string `json:"assdfdff"` Key3 []string `json:"fdsfa"` } `json:"AAA"` }
link to playgrounds
If you do not know the field names in the internal structure, use a map:
type Container struct { Key map[string][]string `json:"AAA"` }
http://play.golang.org/p/gwugHlCPLK
There are more options. Hope this helps you on the right track.
source share