PostgreSQL jsonb - 省略多个嵌套键
PostgreSQL jsonb - omit multiple nested keys
任务是从 jsonb
字段中删除多个嵌套键。
有没有什么方法可以在不编写自定义函数的情况下缩短这个表达式?
SELECT jsonb '{"a": {"b":1, "c": 2, "d": 3}}' #- '{a,b}' #- '{a,d}';
suppose we need to delete more than 2 keys
无法缩短表达式。如果您的目标是将要删除的单个键数组传递给查询,您可以使用 jsonb_set()
和 jsonb_each()
:
with my_table(json_col) as (
values
(jsonb '{"a": {"b":1, "c": 2, "d": 3}}')
)
select jsonb_set(json_col, '{a}', jsonb_object_agg(key, value))
from my_table
cross join jsonb_each(json_col->'a')
where key <> all('{b, d}') -- input
group by json_col -- use PK here if exists
jsonb_set
-----------------
{"a": {"c": 2}}
(1 row)
该解决方案显然更昂贵,但在处理要删除的许多键时可能会很方便。
NVM,想通了)
对于这种特殊情况,我们可以 re-assign 属性 删除键(扁平):
SELECT jsonb_build_object('a', ('{ "b":1, "c": 2, "d": 3 }' - ARRAY['b','d']));
更通用的方法:
SELECT json_col || jsonb_build_object('<key>',
((json_col->'<key>') - ARRAY['key-1', 'key-2', 'key-n']));
对于深层路径不是很有用,但可以用于 1 级嵌套。
任务是从 jsonb
字段中删除多个嵌套键。
有没有什么方法可以在不编写自定义函数的情况下缩短这个表达式?
SELECT jsonb '{"a": {"b":1, "c": 2, "d": 3}}' #- '{a,b}' #- '{a,d}';
suppose we need to delete more than 2 keys
无法缩短表达式。如果您的目标是将要删除的单个键数组传递给查询,您可以使用 jsonb_set()
和 jsonb_each()
:
with my_table(json_col) as (
values
(jsonb '{"a": {"b":1, "c": 2, "d": 3}}')
)
select jsonb_set(json_col, '{a}', jsonb_object_agg(key, value))
from my_table
cross join jsonb_each(json_col->'a')
where key <> all('{b, d}') -- input
group by json_col -- use PK here if exists
jsonb_set
-----------------
{"a": {"c": 2}}
(1 row)
该解决方案显然更昂贵,但在处理要删除的许多键时可能会很方便。
NVM,想通了)
对于这种特殊情况,我们可以 re-assign 属性 删除键(扁平):
SELECT jsonb_build_object('a', ('{ "b":1, "c": 2, "d": 3 }' - ARRAY['b','d']));
更通用的方法:
SELECT json_col || jsonb_build_object('<key>',
((json_col->'<key>') - ARRAY['key-1', 'key-2', 'key-n']));
对于深层路径不是很有用,但可以用于 1 级嵌套。