arrays - 修改 JSON 数组元素

标签 arrays json postgresql

我有一张 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/

相关文章:

spring - 如何使用 spring data jpa 查询 jsonb 列?

java - 如何在插入排序中保持数据配对

java - 在 Java 中将 StringBuffer 转换为字节数组

c - 被调用函数是否应该始终检查 C 中的数组大小?

java - Angular - http 响应未定义

java - 将 Excel 转换为 JSON

c# - 为什么 List<T> 出现 "Index was out of range"异常而不是数组?

c++ - 如何有效地解析 C++ 中的大数据 json 文件(wikidata)?

PostgreSQL 慢 DISTINCT WHERE

json - PostgreSQL 9.5 : Display json data into table