json - 解码嵌套 json 会导致空值

标签 json go struct slice unmarshalling

我正在尝试解码嵌套的 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 是一个空数组。

最佳答案

"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]]

关于json - 解码嵌套 json 会导致空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63951179/

相关文章:

c++ - 结构作为函数的参数 : more efficient to copy or dereference?

c - “fread”动态分配的结构

c - C编译错误中的队列实现

java - 在java中连接两个json对象

windows - 尝试使用 pkg-config 但它不是注册命令

蒙戈数据库 : How to insert additional object into object collection in golang?

Golang os.使用嵌套目录创建路径

php - 开箱即用的 php 目录结构组件

javascript - Orientdb 使用函数返回 JSON

python - 如何使用python批量发布到elasticsearch?