在Postgres中的JSONB列中更改值的类型

时间:2019-07-04 12:16:39

标签: postgresql casting jsonb

我有存储JSON对象的JSONB类型的“主题”列。示例:{"team": "1234", "user": 5678}{"org": 123}或{“ team”:1234}。

我应该使用哪种查询将所有出现的{“ team”:“ 1234”,...}更改为{“ team”:1234,...}?

我尝试过:

UPDATE the_table SET subject = jsonb_set(subject, '{team}', (subject->>'team')::int)

但是我得到了

ERROR: function jsonb_set(jsonb, unknown, integer) does not exist
LINE 2: SET subject = jsonb_set(subject, 'team', (subject->>'team'):... 
                      ^ 
HINT: No function matches the given name and argument types. You might need to add explicit type casts.

1 个答案:

答案 0 :(得分:2)

只需将subject->>'team'结果直接转换为jsonb而不是int。不要忘记添加WHERE过滤器,否则您的第二条记录将被删除。

demo:db<>fiddle

UPDATE the_table 
SET subject = jsonb_set(subject, '{team}', (subject->>'team')::jsonb)
WHERE subject->>'team' IS NOT NULL;
相关问题