【问题标题】:golang nested struct and map [duplicate]golang嵌套结构和映射[重复]
【发布时间】:2016-10-12 21:27:46
【问题描述】:

我是 golang 的新手,我试图将数据库查询结果映射到我的嵌套结构,但我遇到了错误,无法找出最好的方法。该程序假设输出 JSON - 按类别分组的书籍详细信息。

结构如下

type book struct{
  category string
  books []*bookDetails
}

type bookDetails struct{
  name  string
  id    uint
  publisher string.
}

预期的 JSON 输出

[
  {
    "category" : "Ficton",
    "books" : [
               {name:'aaa',id:12,publisher:'one'},
               {name:'bbb',id:13,publisher:'two'}
             ]
  },
 {
    "category" : "suspense",
    "books" : [
               {name:'ccc',id:14,publisher:'three'},
               {name:'ddd',id:15,publisher:'four'}
             ]
  }
]

我不是在这里写 SQL 查询,但请假设类似的数据库模式。以下代码中的 dbRow 是选择查询的输出。以下代码运行良好,但我将所有书籍放在一个数组中,并且我无法弄清楚如何将其按类别分组

detailsMap := make(map[uint][]*details)
for dbRow.Next() {
  var det details
  detErr := dbRow.StructScan(&det)
  detailsMap[det.id] = append(detailsMap[det.id], &det)
}

【问题讨论】:

    标签: json go struct structure


    【解决方案1】:

    关于 SO 的 go 标签的第 1 个问题。

    必须导出结构成员,也就是以大写字母开头。

    type book struct{
      Category string `json:"category"`
      Books []*BookDetails `json:"books"`
    }
    
    type BookDetails struct{
      Name  string `json:"name"`
      ID    uint `json:"id"`
      Publisher string `json:"publisher"`
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2021-12-24
      相关资源
      最近更新 更多