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

SQLC - 如何检索存储为 JSONB 的数据

SQLC - 如何检索存储为 JSONB 的数据

Go
翻阅古今 2023-03-07 16:37:28
我有一个包含字段 JSONB 的简单表:CREATE TABLE IF NOT EXISTS "test_table" (    "id" text NOT NULL,    "user_id" text NOT NULL,    "content" jsonb NOT NULL,    "create_time" timestamptz NOT NULL,    "update_time" timestamptz NOT NULL,    PRIMARY KEY ("id"));我使用一个简单的查询来生成带有 SQLC 的样板文件。-- name: GetTestData :oneSELECT * FROM test_tableWHERE id = $1 LIMIT 1;但是该content属性生成为json.RawMessage.type TestTable struct {    ID          string          `json:"id"`   UserId      string          `json:"user_id"`    Content     json.RawMessage `json:"content"`    CreateTime  time.Time       `json:"create_time"`    UpdateTime  time.Time       `json:"update_time"`}下面是存储在内容列中的 JSON 示例:{  "static": {    "product": [      {        "id": "string",        "elements": {          "texts": [            {              "id": "string",              "value": "string"            }          ],          "colors": [            {              "id": "string",              "value": "string"            }          ],          "images": [            {              "id": "string",              "values": [                {                  "id": "string",                  "value": "string"                }              ]            }          ]        }      }    ]  },  "dynamic": {    "banner": [      {        "id": "string",        "elements": {          "texts": [            {              "id": "string",              "value": "string"            }          ],          "colors": [            {              "id": "string",              "value": "string"            }          ],          "images": [            {              "id": "string",              "values": [                {                  "id": "string",                  "value": "string"                }              ]            }          ]        }      }    ]  }}Static 或 Dynamic 中的嵌套属性是数组。content 属性应该包含一个嵌套对象,我似乎无法提取其中的数据。json.Unrmarshall()似乎只获得顶级属性。有没有办法转换 map[string]interface{}为内容或帮助 SQLC 生成属性作为接口而不是 RawMessage?
查看完整描述

1 回答

?
慕斯王

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

您的 JSON 包含staticdynamic键。您正在解析为 amap[string]json.RawMessage然后尝试从地图中检索Static和检索Dynamic(注意大写)。

修复地图键(即json.Unmarshal(res["static"], &static)),您的代码可能会工作。更好的解决方案可能是在尝试解组之前检查密钥是否存在。


查看完整回答
反对 回复 2023-03-07
  • 1 回答
  • 0 关注
  • 76 浏览
慕课专栏
更多

添加回答

举报

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