【问题标题】:Cast postgresql jsonb value as array of int and remove element from it将 postgresql jsonb 值转换为 int 数组并从中删除元素
【发布时间】:2019-08-22 19:21:27
【问题描述】:

我正在尝试从存储在 db 中的 jsonb 值类型中的 json 中的 int 的 jsonb 数组中删除 int 值。

我有一个 json 值,比如:

select '{"a":[1,3]}'::jsonb->'a'

?column?
----------
[1, 3]
(1 row)

我想从中删除“1”,就像这样:

select array_remove(ARRAY[1,1,2,3], 1);
 array_remove
--------------
 {2,3}
(1 row)

但如果我这样做:

select array_remove(array('{"a":[1,3]}'::jsonb->'a'), 1);

或:

select array_remove('{"a":[1,3]}'::jsonb->'a'::text::int[], 1);

我有如下错误:

operator does not exist: jsonb -> integer[]

如何将 json 值转换为数组以从中删除值?

【问题讨论】:

    标签: arrays json postgresql jsonb


    【解决方案1】:

    现在,您基本上必须将数组扩展为单个值,过滤这些值,然后创建一个新数组:

    with data(original) as (VALUES ('{"a":[1,1,2,3]}'::jsonb), ('{"a":[2,3,4,5,1]}'::jsonb))
    select original->'a', filtered
    from data
    JOIN LATERAL (SELECT jsonb_agg(value) as filtered 
                  from jsonb_array_elements(original->'a') j(value) 
                  WHERE value::int != 1) as filtered ON TRUE;
        ?column?     |   filtered
    -----------------+--------------
     [1, 1, 2, 3]    | [2, 3]
     [2, 3, 4, 5, 1] | [2, 3, 4, 5]
    
    

    在 postgres 12 中,您将能够使用 jsonb_path 函数。语法有点难解析,但不涉及任何连接:

    with data(original) as (VALUES ('{"a":[1,1,2,3]}'::jsonb), ('{"a":[2,3,4,5,1]}'::jsonb))
    select original->'a', 
           jsonb_path_query_array(original, '$.a[*] ? (@ != $filter)', '{"filter":1}')
    from data;
        ?column?     | jsonb_path_query_array
    -----------------+------------------------
     [1, 1, 2, 3]    | [2, 3]
     [2, 3, 4, 5, 1] | [2, 3, 4, 5]
    (2 rows)
    

    【讨论】:

    • 谢谢杰里米,我测试了它,它似乎有效。但为什么我不能只使用 array_remove 函数?实际上我需要在我的原始 json 字段中更新该数组,现在我正在尝试实现它。如果你有一些建议会很有用。
    • array_remove 用于数组类型,而不是 json 或 jsonb。您可以使用 jsonb_array_elements 扩展 json 数组,使用 array_agg,创建一个 int[],然后使用 array_remove,但这只是一个额外的步骤。
    猜你喜欢
    • 1970-01-01
    • 2017-03-10
    • 2015-07-12
    • 1970-01-01
    • 2017-02-17
    • 2022-05-25
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    相关资源
    最近更新 更多