【问题标题】:Unmarshaling JSON with nested map[string]interface使用嵌套的 map[string] 接口解组 JSON
【发布时间】: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 数组,而不是对象。

标签: json go interface


【解决方案1】:

要处理这种嵌套的 json 对象,理想情况下您应该将它们分解为单个对象而不是接口,因为它们更安全

为简单起见创建自己的结构,如下所示:

type Xtoy struct {
    Num1 int `json:"1"`
    Num2 int `json:"2"`
    Num3 int `json:"3"`
}
type Atob struct {
    Num1 int `json:"1"`
    Num2 int `json:"2"`
    Num3 int `json:"3"`
}
type Mton struct {
    Num1 int `json:"1"`
    Num2 int `json:"2"`
    Num3 int `json:"3"`
}
type Item struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}
type Product struct {
    ID   int    `json:"id"`
    Type string `json:"type"`
}
type Num1 struct {
    Product Product `json:"product"`
}
type Details struct {
    Num1 Num1 `json:"1"`
}
type Details struct {
    Details Details `json:"details"`
}
type Num1 struct {
    Item    Item    `json:"item"`
    Details Details `json:"details"`
}
type Itemdetails struct {
    Num1 Num1 `json:"1"`
}
type Data struct {
    Xtoy        Xtoy        `json:"xtoy"`
    Atob        Atob        `json:"atob"`
    Mton        Mton        `json:"mton"`
    Itemdetails Itemdetails `json:"itemdetails"`
}



type Finale struct {
        Data Data   `json:"data"`
        Date string `json:"Date"`
 }

【讨论】:

  • 问题是字段数量变化,xtoy可能有3个字段到300个字段
猜你喜欢
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 2019-09-04
  • 2021-11-17
  • 2020-02-06
  • 2022-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多