gpt4 book ai didi

arrays - 编码 JSON 导致空结构

转载 作者:行者123 更新时间:2023-12-01 22:40:46 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





json.Unmarshal returning blank structure

(1 个回答)



Why struct fields are showing empty?

(1 个回答)


2年前关闭。




我有以下 JSON 结构:

dataJson := `{"data1" : [["a",1]["b",2]], "data2": ["a","b",3]}`

并想用 Go 解码它。我正在尝试以下代码:
type myData struct {
row map[string][][]interface{} `json:"data1"`
column map[string][]interface{} `json:"data2"`
}

var arr myData

_ = json.Unmarshal([]byte(dataJson), &arr)

但我得到空数据:
Unmarshaled: {map[] map[]}

知道如何解析这样的 JSON 结构吗?

最佳答案

第一个问题是必须导出结构字段(名称以大写字母开头)。见 Why struct fields are showing empty?更多细节。

接下来,您的输入 JSON 无效,data1 的元素之间缺少逗号大批。它应该是:

{"data1" : [["a",1],["b",2]], "data2": ["a","b",3]}

三、 data1data2是 JSON 数组,所以你必须在 Go 中使用 slice 而不是 map 。

像这样的东西:
type myData struct {
Row [][]interface{} `json:"data1"`
Column []interface{} `json:"data2"`
}

json.Unmarshal() 返回一个错误,在 Go 中永远不要忽略错误。您至少可以打印它们,这样您就会知道有些不对劲:
dataJson := `{"data1" : [["a",1],["b",2]], "data2": ["a","b",3]}`

var arr myData
if err := json.Unmarshal([]byte(dataJson), &arr); err != nil {
log.Println(err)
}
log.Printf("Unmarshaled: %v", arr)

此输出(在 Go Playground 上尝试):
2009/11/10 23:00:00 Unmarshaled: {[[a 1] [b 2]] [a b 3]}

关于arrays - 编码 JSON 导致空结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59629894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com