如何在类型结构中表示动态键?

huangapple go评论99阅读模式
英文:

How to present dynamic keys in a type struct?

问题

我有一个包含JSONB字段的PostgreSQL表。可以通过以下方式创建该表:

create table mytable
(
  id         uuid primary key     default gen_random_uuid(),
  data       jsonb       not null
);

在上面的示例中,我使用"0x101"和"0x102"来表示两个UID。实际上,它可能有更多的UID。

我正在使用jackc/pgx来读取该JSONB字段。

以下是我的代码:

import (
	"context"
	"fmt"
	"github.com/jackc/pgx/v4/pgxpool"
)

type Data struct {
	UserRoles struct {
		UID []string `json:"uid,omitempty"`
		// 上面的代码不起作用,因为没有名为"uid"的固定字段。
		// 相反,它们是"0x101"、"0x102"等等。
	} `json:"user_roles,omitempty"`
}

type MyTable struct {
	ID   string
	Data Data
}

pg, err := pgxpool.Connect(context.Background(), databaseURL)
sql := "SELECT data FROM mytable"
myTable := new(MyTable)
err = pg.QueryRow(context.Background(), sql).Scan(&myTable.Data)
fmt.Printf("%v", myTable.Data)

如上面的注释所提到的,上述代码不起作用。

如何在类型结构中表示动态键,或者如何返回所有JSONB字段的数据?谢谢!

英文:

I have a PostgreSQL table which has a JSONB filed. The table can be created by

create table mytable
(
  id         uuid primary key     default gen_random_uuid(),
  data       jsonb       not null,
);

insert into mytable (data)
values ('{
  "user_roles": {
    "0x101": [
      "admin"
    ],
    "0x102": [
      "employee",
      "customer"
    ]
  }
}
'::json);

In above example, I am using "0x101", "0x102" to present two UIDs. In reality, it has more UIDs.

I am using jackc/pgx to read that JSONB field.

Here is my code

import (
	"context"
    "fmt"
	"github.com/jackc/pgx/v4/pgxpool"
)

type Data struct {
	UserRoles struct {
		UID []string `json:"uid,omitempty"`
        // ^ Above does not work because there is no fixed field called "uid".
        // Instead they are "0x101", "0x102", ...
	} `json:"user_roles,omitempty"`
}
type MyTable struct {
	ID   string
	Data Data
}

pg, err := pgxpool.Connect(context.Background(), databaseURL)
sql := "SELECT data FROM mytable"
myTable := new(MyTable)
err = pg.QueryRow(context.Background(), sql).Scan(&myTable.Data)
fmt.Printf("%v", myTable.Data)

As the comment inside mentions, the above code does not work.

How to present dynamic keys in a type struct or how to return all JSONB field data? Thanks!

答案1

得分: 1

请将您的数据结构编辑如下:

type Data struct {
    UserRoles map[string][]string `json:"user_roles,omitempty"`
}

如果您正在使用类似于https://github.com/google/uuid的包来处理UUID,您还可以将UUID类型用作映射的键类型。

但请注意,如果在JSON对象的user_roles字段中为特定用户(具有相同的UUID)有多个条目,只会获取其中一个条目。

英文:

edit your Data struct as follows,

type Data struct {
    UserRoles map[string][]string `json:"user_roles,omitempty"`
}

you can also use a uuid type as the map's key type if you are using a package like https://github.com/google/uuid for uuids.

However please note that this way if you have more than one entry in the json object user_roles for a particular user(with the same uuid), only one will be fetched.

huangapple
  • 本文由 发表于 2021年8月1日 19:44:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/68610075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定