http://play.golang.org/p/f6ilWnWTjm
我正在尝试解码以下字符串,但只得到空值。
如何在 Go 中解码嵌套的 JSON 结构?
我想将以下内容转换为 map 数据结构。
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 中的嵌套结构。
这是一个如何处理示例 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)
}
您还可以为内部结构使用匿名类型:
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"`
}
如果您不知道内部结构中的字段名称,则使用映射:
type Container struct {
Key map[string][]string `json:"AAA"`
}
http://play.golang.org/p/gwugHlCPLK
还有更多选择。希望这能让您走上正轨。
关于json - 解码嵌套的 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25966567/