dongzhi1851 2016-10-12 21:27
浏览 132

golang嵌套的结构和映射[重复]

This question already has an answer here:

I am new to golang and trying to map database query result to my struct which is nested but I am getting errors and not able to figure out the best way to do it. This program is suppose to out JSON - book details group by categories.

Struct is as follows

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

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

Expected JSON output

[
  {
    "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'}
             ]
  }
]

I am not writing SQL query here but please assume similar kind of database schema. dbRow in following code is output of select query. Following code is working fine but I am getting all the books in one array, and I am not able to figure out how can I make it group by categories.

detailsMap := make(map[uint][]*details)
for dbRow.Next() {
  var det details
  detErr := dbRow.StructScan(&det)
  detailsMap[det.id] = append(detailsMap[det.id], &det)
}
</div>
  • 写回答

1条回答 默认 最新

  • dscrb00804 2016-10-13 04:26
    关注

    The #1 asked question on SO's go tag.

    Struct members has to be exported, aka start with capital letter.

    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"`
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私