猿问

在 Golang Struct 中分配 DB 列

我在数据库中有两个表,例如零售商和产品。零售商有许多产品。


以下是我在 golang 中定义的结构。


type Retailers struct {

  Id int 

  Name string

  Products []Product

}


type Product struct {

  Id int 

  Description string

  Url string 

}

以下是用于从数据库中获取数据的查询。


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

使用上面的结构和查询我希望形成如下的 json


{

    "id": "DFT",

    "name": "Amazon",

    "products":[

        {

            "id":"APP0001",

            "description":"Iphone5s",

            "url":"www.Iphone5s.com"

        },

        {

            "id":"APP0002",

            "description":"Iphone6s",

            "url":"www.Iphone6s.com"

        }

    ]

}

如何使用 golang 实现这一目标?


摇曳的蔷薇
浏览 190回答 1
1回答

MMMHUHU

您需要在结构定义中指定结构标签: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"`}
随时随地看视频慕课网APP

相关分类

Go
我要回答