gpt4 book ai didi

json - 去解析数组的JSON数组

转载 作者:IT王子 更新时间:2023-10-29 01:38:53 25 4
gpt4 key购买 nike

我有这样的数据

"descriptionMap": [[[1,2], "a"], [[3,4], "b"]]

我试着用

解码它
  DescriptionMap []struct {
OpcodeTableIdPair []int
OpcodeDescription string
} `json:"descriptionMap"`

但我一直得到空数组,

[[{[] } {[] }]]

最佳答案

您有一个非常不幸的 JSON 架构,它将数组视为对象。在这种情况下你能做的最好的事情是这样的:

type Body struct {
DescriptionMap []Description `json:"descriptionMap"`
}

type Description struct {
IDPair []int
Description string
}

func (d *Description) UnmarshalJSON(b []byte) error {
arr := []interface{}{}
err := json.Unmarshal(b, &arr)
if err != nil {
return err
}

idPair := arr[0].([]interface{})
d.IDPair = make([]int, len(idPair))
for i := range idPair {
d.IDPair[i] = int(idPair[i].(float64))
}

d.Description = arr[1].(string)

return nil
}

Playground :https://play.golang.org/p/MPho12GJfc .

请注意,如果 JSON 中的任何类型不匹配,这将导致 panic 。您可以创建一个更好的版本,在这种情况下返回错误。

关于json - 去解析数组的JSON数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057016/

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