Postgres更新JSONB字符串到数组

发布于 2025-01-30 00:33:01 字数 781 浏览 4 评论 0 原文

我有一个表列2是JSONB,我想更改列2是数组的字符串的值。 的结果具有“一个”为[一个“一个”]和“第三” be [third']

table1

column2 我希望Column2
first [一个“一个”,“两个”,“
] “第三”
第四 4

我应该如何更新值? 这是我尝试的:

UPDATE table 
SET columnn2 = ARRAY[value]::JSONB 
WHERE jsonb_typeof(column2)!='array';

I have a table where column2 is type JSONB and I would like to alter the values where column2 is a string to an array. I would like the result for column2 to have "one" be ["one"] and "third" be ["third"]

Table

column1 column2
First ["one", "two", "three"]
Second "one"
Third "third"
Third 4

How should I be updating the value?
Here's what I have tried:

UPDATE table 
SET columnn2 = ARRAY[value]::JSONB 
WHERE jsonb_typeof(column2)!='array';

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

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

发布评论

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

评论(2

喜爱纠缠 2025-02-06 00:33:01

使用 JSONB_BUILD_ARRAY()函数:

update my_table set
    column2 = jsonb_build_array(column2)
where jsonb_typeof(column2) != 'array';

阅读有关函数在文档中。

Use the jsonb_build_array() function:

update my_table set
    column2 = jsonb_build_array(column2)
where jsonb_typeof(column2) != 'array';

Test it in db<>fiddle.

Read about the function in the documentation.

浅沫记忆 2025-02-06 00:33:01

一种选项是使用串联操作员( || )用方括号和铸件以及 text> text ,然后重新铸造到< code>JSONB such as

UPDATE tab
   SET column2 = ('['||column2::TEXT||']')::JSONB
 WHERE jsonb_typeof(column2) != 'array'

Demo

One option is to use concatenation operators(||) to wrap up the expresion with square brackets along with casting to TEXT, then recasting to JSONB such as

UPDATE tab
   SET column2 = ('['||column2::TEXT||']')::JSONB
 WHERE jsonb_typeof(column2) != 'array'

Demo

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