我有一个简单的表,其中有一个字段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"`
}下面是存储在content列中的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"
}
]
}
]
}
}
]
}
}静态或动态中的嵌套属性是数组。
content属性应该包含一个嵌套对象,而我似乎无法提取其中的数据。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
发布于 2022-10-31 05:03:33
JSON包含static和dynamic键。您正在解析为一个map[string]json.RawMessage,然后尝试从映射中检索Static和Dynamic (注意大写)。
修复映射键(即json.Unmarshal(res["static"], &static)),您的代码将可能有用。更好的解决方案可能是在尝试解除封送之前检查密钥是否存在。
https://stackoverflow.com/questions/74258327
复制相似问题