我正在尝试解码嵌套的 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/