dqrm8199 2016-05-17 15:12
浏览 33
已采纳

在Golang结构中分配DB列

I have two tables like Retailers and products in database. Retailer has many Products.

They following are the structs I have defined in golang.

type Retailers struct {
  Id int 
  Name string
  Products []Product
}

type Product struct {
  Id int 
  Description string
  Url string 
}

The following is the query am using to fetch data from Database.

select r.id, r.name, p.id, p.description, p.url from retailers r JOIN products on r.id = r.retailer_id

Using the above struct and query I wish to form the json as below

{
    "id": "DFT",
    "name": "Amazon",
    "products":[
        {
            "id":"APP0001",
            "description":"Iphone5s",
            "url":"www.Iphone5s.com"
        },
        {
            "id":"APP0002",
            "description":"Iphone6s",
            "url":"www.Iphone6s.com"
        }
    ]
}

How can I achieve this using golang?

  • 写回答

1条回答 默认 最新

  • duanshan1977 2016-05-17 15:17
    关注

    You need to specify struct tags in your struct definition:

    type Retailers struct {
      Id int `json:"id"`
      Name string `json:"name"`
      Products []Product `json:"products"`
    }
    
    type Product struct {
      Id int `json:"id"`
      Description string `json:"description"`
      Url string `json:"url"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)