为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Go 中进行嵌套的 JSON 响应?

如何在 Go 中进行嵌套的 JSON 响应?

Go
当年话下 2023-06-19 11:08:08
我是 Go 的新手,需要一些帮助。在我的 PostgreSQL 数据库中,我有 4 个表。他们称:surveys、questions和options。surveys_questions_options它们看起来像这样:surveys桌子:| survey_id (uuid4)                    | survey_name (varchar) ||--------------------------------------|-----------------------|| 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | April                 || b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | May                   |questions桌子:| question_id (int) | question_text (text)         ||-------------------|------------------------------|| 1                 | What is your favorite color? |options桌子:| option_id (int)   | option_text (text) ||-------------------|--------------------|| 1                 | red                || 2                 | blue               || 3                 | grey               || 4                 | green              || 5                 | brown              |surveys_questions_options表格结合了所有前三个表格的数据:| survey_id                            | question_id | option_id ||--------------------------------------|-------------|-----------|| 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | 1           | 1         || 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | 1           | 2         || 0cf1cf18-d5fd-474e-a8be-754fbdc89720 | 1           | 3         || b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | 1           | 3         || b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | 1           | 4         || b9fg55d9-n5fy-s7fe-s5bh-856fbdc89720 | 1           | 5         |如何在 Go 中进行嵌套的 JSON 响应?我使用 GORM 库。我想要这样的 JSON 响应:[    {        "survey_id": "0cf1cf18-d5fd-474e-a8be-754fbdc89720",        "survey_name": "April",        "questions": [            {                "question_id": 1,                "question_text": "What is your favorite color?",                "options": [                    {                        "option_id": 1,                        "option_text": "red"                    },
查看完整描述

3 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

我们从您的代码中遗漏了一些范围,因此很难为您指明正确的方向。您是在询问查询 GORM 以便获得[]Survey,还是在询问编组[]Survey?无论如何,正如 slomek 所回答的那样,您也应该将标签添加到问题中。



查看完整回答
反对 回复 2023-06-19
?
撒科打诨

TA贡献1934条经验 获得超2个赞

我不确定 GORM 部分,但是对于 JSON,您还需要在嵌套对象上添加结构标签:


type Survey struct {

  ...

  Questions []Question `json:"questions"`

}


type Question struct {

  ...

  Options []Option `json:"options"`

}


查看完整回答
反对 回复 2023-06-19
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

但是,试试这个:To fetch nested data in m2m relation


type Survey struct {

  gorm.Model

  SurveyID string       `gorm:"primary_key" json:"survey_id"`

  SurveyName string     `gorm:"not null" json:"survey_name"`

  Questions []*Question `gorm:"many2many:survey_questions;"`

}


surveys := []*model.Survey{}

db := dbSession.Where(&model.Survey{SurveyID: id}).Preload("Questions").Find(&surveys)


查看完整回答
反对 回复 2023-06-19
  • 3 回答
  • 0 关注
  • 119 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信