登录
首页 >  Golang >  Go问答

解析 JSON 数据中的嵌套映射接口

来源:stackoverflow

时间:2024-02-22 13:36:25 149浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《解析 JSON 数据中的嵌套映射接口》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我有一个 json,它就像一个嵌套的 map[string]interface{},我似乎无法解析它,它看起来像

{
  "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 结构的嵌套结构


解决方案


要处理这种嵌套的 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"`
 }

今天关于《解析 JSON 数据中的嵌套映射接口》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>