英文:
Go parse JSON array of array
问题
我有这样的数据
"descriptionMap": [[[1,2], "a"], [[3,4], "b"]]
我试图用以下方式解码它
DescriptionMap []struct {
OpcodeTableIdPair []int
OpcodeDescription string
} `json:"descriptionMap"`
但是我一直得到空数组
[[{[] } {[] }]]
英文:
I have data like this
"descriptionMap": [[[1,2], "a"], [[3,4], "b"]]
and I was trying to decode it with
DescriptionMap []struct {
OpcodeTableIdPair []int
OpcodeDescription string
} `json:"descriptionMap"`
but I keep on getting empty arrays,
[[{[] } {[] }]]
答案1
得分: 3
你有一个非常不幸的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
}
请注意,如果JSON中的任何类型不匹配,这段代码将会引发panic。你可以创建一个更好的版本,在这种情况下返回错误。
英文:
You have a very unfortunate JSON schema which treats arrays as objects. The best you can do in this situation is something like this:
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.
Notice though that this will panic if any of the types in the JSON don't match. You can create a better version which returns errors in such cases.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论