json - 解组嵌套 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 是一个空数组。
解决方案
"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]]
推荐阅读
- python - 如何让python代理观察?
- unit-testing - 使用 Jest Enzyme 进行异步/等待测试
- git - 如何处理 PowerShell ISE 上的 Git 错误?
- html - 自由格式文本表单输入框
- aws-certificate-manager - aws acm 导入证书抛出 LimitExceededException
- javascript - 如何从使用 addEventListener 添加的事件的元素中删除类?
- python - 解决具有特定约束的分配问题
- c++ - 在不同的浮点精度之间切换时使用我自己的 std::mersenne_twister_engine 模板参数
- excel - 我需要在 Excel 中使用 PV 而不是 NPV。但是我无法理解为什么它给出不同的值
- powershell - 如何使用 Get-ChildItem 定位特定的父/子?