【发布时间】:2020-06-29 07:50:29
【问题描述】:
我有一个类似于嵌套 map[string]interface{} 的 json,我似乎无法解析它,它看起来像
{
"data": {
"xtoy": {
"1": 2,
"2": 3,
"3": 4
},
"atob": {
"1": 4,
"2": 5,
"3": 6
},
"mton": {
"1": 9,
"2": 8,
"3": 7
},
"itemdetails": {
"1": {
"item": {
"id": 1,
"name": "item1"
},
"details": {
"details": {
"1": {
"product": {
"id": 1,
"type": "premium"
}
}
}
}
}
}
},
"Date": "2011-07-01"
}
有什么方法可以简单的解决这个问题吗?我有点不知所措。 编辑 我试过制作一个像
这样的结构type Data struct{
xtoy map[string]interface{} `mapstructure:"xtoy " json:"xtoy "`
atob map[string]interface{} `mapstructure:"atob" json:"atob"`
mton map[string]interface{} `mapstructure:"mton" json:"mton"`
itemdetails[]CustomStruct `mapstructure:"itemdetails" json:"itemdetails"`
}
现在前 3 个可以工作,但是当我进入 itemdetails 时,我需要访问接口内的字段,但要添加到问题 itemdetails 是一个接口数组。 CustomStruct 是一个嵌套结构,遵循 json 结构
【问题讨论】:
-
你试过什么?你有什么问题?发布您的代码。
-
@icza 我添加了更多代码,这有帮助吗?
-
如果您添加代码,请显示您的代码应该处理的实际 JSON 输入。瞄准minimal reproducible example。
-
@icza 我添加了一些实际代码,但自定义结构代码太大,够吗?
-
您必须导出结构字段(以大写字母开头)。此外,
"itemdetails"在 JSON 中是一个 JSON 对象,你必须为它使用一个结构。Data.itemdetails在 Go 中是一个切片。切片可用于解组 JSON 数组,而不是对象。