从 JSON 列的数组属性中删除值

问题描述 投票:0回答:1

我在 PostgreSQL(版本 13.12)表中有一个

json
(不是
jsonb
)列,我想从中删除数组属性的特定值。

例如,在下表 (db-fiddle) 中,我想从

actions
属性中删除所有出现的“D”。

DROP TABLE IF EXISTS test;
CREATE TABLE test (
  data JSON
);
INSERT INTO test VALUES
  ('{"name": "Alice", "actions": ["B", "C", "D"]}'),
  ('{"name": "Charles", "actions": ["C", "D", "E"]}');
SELECT * FROM test;

我如何通过查询来做到这一点?

json postgresql
1个回答
0
投票
select json_build_object('name', name, 'actions', json_agg(action)) as data
from (select data ->> 'name' as name, t.action
      from test,
           lateral json_array_elements_text(data -> 'actions') t(action)
      where action <> 'D') tmp
group by name;

输出:

数据 |

{“名称”:“爱丽丝”,“动作”:[“B”,“C”]}| {“名称”:“查尔斯”,“行动”:[“C”,“E”]}|

© www.soinside.com 2019 - 2024. All rights reserved.