首页 > 解决方案 > 解组嵌套 json 会导致空值

问题描述

我正在尝试解组嵌套的 json。一个键的值是一个 json 数组。数据如下所示:

jsonData := `{"Key0": 1,
                            "Key1": [
                                {"SubKey0": "Id0", "SubKey1": 0, "SubKey2": "rndm0"},   
                                {"SubKey1": "Id1", "SubKey1": 1, "SubKey2": "rndm1"}
                                ]
             }'

数组中的元素数量是未知且可变的。

目标是得到一个结构,其中包含数组的数据:

我尝试了以下代码:

            package main

            import (
                "encoding/json"
                "fmt"
            )

            type Container struct {
                Key0 int
                Key1 []string
            }

            var container Container

            func main() {
                jsonData := `{"Key0": 1,
                            "Key1": [
                                {"SubKey0": "string0", "SubKey1": 0},   
                                {"SubKey0": "string1", "SubKey1": 1}
                                ]
                            }`
                json.Unmarshal([]byte(jsonData), &container)
                fmt.Printf(string(container.Key0))
                fmt.Printf(fmt.Sprint(container.Key1))
            }

但这会导致 container.Key1 是一个空数组。

标签: jsongostructsliceunmarshalling

解决方案


"Key0"在 JSON 中是一个数字,而不是一个string.

"Key1"在 JSON 中是一个对象数组,它不是一个string.

所以使用这个 Go 结构来建模你的 JSON:

type Container struct {
    Key0 int
    Key1 []map[string]interface{}
}

解析 JSON:

jsonData := `{"Key0": 1,
                        "Key1": [
                            {"SubKey0": "string0", "SubKey1": 0},   
                            {"SubKey0": "string1", "SubKey1": 1}
                            ]
                        }`
if err := json.Unmarshal([]byte(jsonData), &container); err != nil {
    panic(err)
}
fmt.Println(container.Key0)
fmt.Println(container.Key1)

哪些输出(在Go Playground上尝试):

1
[map[SubKey0:string0 SubKey1:0] map[SubKey0:string1 SubKey1:1]]

推荐阅读