生成的Postgres始终jsonb,指的是字符串中的其他列

发布于 2025-02-07 22:03:20 字数 448 浏览 2 评论 0原文

试图生成一个看起来像这样的JSONB列: [“ C:cluster-X”,“ NS:cluster-x/namespace-1”]

群集和命名空间将从其他字段中获取。我正在努力寻找一种成功的方法

,在这里也可以成功地将数组文字很好,例如'{c:cluster-x,ns:cluster-x/namespace-1}'

i尝试这样的事情:

ALTER TABLE my_table ADD COLUMN resources jsonb GENERATED ALWAYS AS ('["c:"' || my_table."clusterName" || ']'::jsonb) STORED;

但是得到: 详细信息:预期的JSON值,但找到了“]”。

Postgres版本13.4

Trying to generate a jsonb column that will look like this:
["c:cluster-x", "ns:cluster-x/namespace-1"]

The cluster and namespace will be taken from other fields. I'm struggling with finding a way to concat it successfully

Also an array literal will be fine here, like this '{c:cluster-x, ns:cluster-x/namespace-1}'

I tried something like this:

ALTER TABLE my_table ADD COLUMN resources jsonb GENERATED ALWAYS AS ('["c:"' || my_table."clusterName" || ']'::jsonb) STORED;

but getting:
Detail: Expected JSON value, but found "]".

postgres version 13.4

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

递刀给你 2025-02-14 22:03:20

您将单个字符]作为JSONB。这就是为什么您会遇到此错误。另外,<代码>:在键和值之间缺少(放错了位置?)。

这应该起作用:

ALTER TABLE my_table ADD COLUMN resources jsonb 
GENERATED ALWAYS AS (('[{"c":"' || "clusterName" || '"}]')::jsonb) STORED;

注意:如果列clusername为null,则该解决方案将返回null。

演示:

You are casting a single character ] as jsonb. That's why you're getting this error. Also, the : is missing (misplaced?) between key and value.

This should work:

ALTER TABLE my_table ADD COLUMN resources jsonb 
GENERATED ALWAYS AS (('[{"c":"' || "clusterName" || '"}]')::jsonb) STORED;

Note: This solution will return NULL if the column clusterName is NULL.

Demo: db<>fiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文