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

我有一个包含字段 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 :one

SELECT * FROM test_table

WHERE 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?



翻阅古今
浏览 77回答 1
1回答

慕斯王

您的 JSON 包含static和dynamic键。您正在解析为 amap[string]json.RawMessage然后尝试从地图中检索Static和检索Dynamic(注意大写)。修复地图键(即json.Unmarshal(res["static"], &static)),您的代码可能会工作。更好的解决方案可能是在尝试解组之前检查密钥是否存在。
打开App,查看更多内容
随时随地看视频慕课网APP