SQLC - JSONB 数据的检索方法
时间:2024-03-18
浏览:201
作者:佚名
SQLC 是一种用于生成数据库查询样板代码的工具。当从数据库中检索 JSONB 数据时,默认情况下,SQLC 会将内容属性生成为 json.rawmessage,这使得难以提取嵌套数据。为了解决此问题,可以将属性显式地转换为 map[string]interface{} 类型,从而允许访问嵌套对象。通过使用 json.Unmarshal() 函数,可以将 json.rawmessage 解组到 map[string]interface{} 中,从而可以轻松地检索和处理嵌套数据。
我有一个简单的表,其中有一个 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"
}
]
}
]
}
}
]
}
}
静态或动态内的嵌套属性是数组。
内容属性应该包含一个嵌套对象,但我似乎无法提取其中的数据。 json.unrmarshall() 似乎只获得顶级属性。有没有办法投
map[string]interface{} 到内容或帮助 sqlc 将属性生成为接口而不是 rawmessage?
我试图解决这个问题,只是像这样解组原始消息:
var res map[string]json.RawMessage
if err := json.Unmarshal(testingData.Content, &res); err != nil {
return nil, status.Errorf(codes.Internal, "Serving data err %s", err)
}
var static pb.Static
if err := json.Unmarshal(res["Static"], &static); err != nil {
return nil, status.Errorf(codes.Internal, "Static data err %s", err)
}
var dynamic pb.Dynamic
if err := json.Unmarshal(res["Dynamic"], &dynamic); err != nil {
return nil, status.Errorf(codes.Internal, "Dynamic data err %s", err)
}
我在解组有效负载时做错了什么,但我不知道到底是什么。
这是一个示例演示:go.dev/play/p/9e7a63hnmea
正确答案
您的 JSON 包含 Static 和 Dynamic 密钥。您正在解析为 map[string]json.RawMessage,然后尝试从地图中检索 Static 和 Dynamic (注意大小写)。
修复映射键(即 json.Unmarshal(res["static"], &static)),您的代码将为 probably work。更好的解决方案可能是在尝试解组键之前检查键是否存在。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《SQLC - JSONB 数据的检索方法》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
