我有一张 table
id int | data json
有数据:
1 | [1,2,3,2]
2 | [2,3,4]
我想修改行删除数组元素(int)2
预期结果:
1 | [1,3]
2 | [3,4]
最佳答案
正如 a_horse_with_no_name 在他的评论中建议的那样,在这种情况下正确的数据类型是 int[]。但是,您可以将 json 数组转换为 int[],使用 array_remove()
并将结果转换回 json:
with my_table(id, data) as (
values
(1, '[1,2,3,2]'::json),
(2, '[2,3,4]')
)
select id, to_json(array_remove(translate(data::text, '[]', '{}')::int[], 2))
from my_table;
id | to_json
----+---------
1 | [1,3]
2 | [3,4]
(2 rows)
另一种可能性是使用 json_array_elements()
取消嵌套数组,消除不需要的元素并聚合结果:
select id, json_agg(elem)
from (
select id, elem
from my_table,
lateral json_array_elements(data) elem
where elem::text::int <> 2
) s
group by 1;
关于arrays - 修改 JSON 数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43474206/