解组嵌套的JSON结构 [英] Unmarshal nested JSON structure
问题描述
http://play.golang.org/p/f6ilWnWTjm
我正在尝试解码以下字符串,但仅获取空值.
I am trying to decode the following string but only getting null values.
如何在Go中解码嵌套的JSON结构?
How do I decode nested JSON structure in Go?
我想将以下内容转换为地图数据结构.
I want to convert the following to map data structure.
package main
import (
"encoding/json"
"fmt"
)
func main() {
jStr := `
{
"AAA": {
"assdfdff": ["asdf"],
"fdsfa": ["1231", "123"]
}
}
`
type Container struct {
Key string `json:"AAA"`
}
var cont Container
json.Unmarshal([]byte(jStr), &cont)
fmt.Println(cont)
}
推荐答案
在Go中使用嵌套结构以匹配JSON中的嵌套结构.
Use nested structs in Go to match the nested structure in JSON.
以下是如何处理示例JSON的一个示例:
Here's one example of how to handle your example JSON:
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)
}
您还可以对内部结构使用匿名类型:
You can also use an anonymous type for the inner struct:
type Container struct {
Key struct {
Key2 []string `json:"assdfdff"`
Key3 []string `json:"fdsfa"`
} `json:"AAA"`
}
或内部和外部结构:
var cont struct {
Key struct {
Key2 []string `json:"assdfdff"`
Key3 []string `json:"fdsfa"`
} `json:"AAA"`
}
如果您不知道内部结构中的字段名称,请使用地图:
If you don't know the field names in the inner structure, then use a map:
type Container struct {
Key map[string][]string `json:"AAA"`
}
http://play.golang.org/p/gwugHlCPLK
还有更多选择.希望这能使您走上正确的轨道.
There are more options. Hopefully this gets you on the right track.
这篇关于解组嵌套的JSON结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!