gpt4 book ai didi

sql - 从 JsonB 数组中删除数字项

转载 作者:行者123 更新时间:2023-12-03 21:56:26 26 4
gpt4 key购买 nike

我有 jsonb带有嵌套 JSON 数组的值并需要删除一个元素:

{"values": ["11", "22", "33"]}

jsonb_set(column_name, '{values}', ((column_name -> 'values') - '33')) -- WORKS!

我也有类似的 jsonb值与 号码 , 不是字符串:
{"values": [11, 22, 33]}

jsonb_set(column_name, '{values}', ((column_name -> 'values') - 33)) -- FAILS!

在这种情况下 33用作数组的索引。

当这些项目是数字时,如何从 JSON 数组中删除项目?

最佳答案

两个断言:

  • 许多 Postgres JSON 函数和运算符都针对 key 在键/值对中。 字符串 ( "abc""33" )在 JSON 数组中被视为没有值的键。但是数字( 33123.45 )数组元素被视为值。
  • 当前有 的三种变体- 运算符(operator)。其中两个在这里申请。 As the recently clarified manual describes (目前/开发):

    Operator
          Description
          Example(s)
    :---------------------
    jsonb - textjsonb
          Deletes a key (and its value) from a JSON object, or matching string value(s) from a JSON array.
          '{"a": "b", "c": "d"}'::jsonb - 'a'{"c": "d"}
          '["a", "b", "c", "b"]'::jsonb - 'b'["a", "c"]
    ...
    jsonb - integerjsonb
          Deletes the array element with specified index (negative integers count from the end).
          Throws an error if JSON value is not an array.
          '["a", "b"]'::jsonb - 1["a"]


  • 正确的操作数是 numeric literal , Postgres operator type resolution到达后来的变体。

    不幸的是,由于断言 1,我们不能使用前一个变体开始。

    所以我们必须使用 解决方法 喜欢:
    SELECT jsonb_set(column_name
    , '{values}'
    , (SELECT jsonb_agg(val)
    FROM jsonb_array_elements(t.column_name -> 'values') x(val)
    WHERE val <> jsonb '33')
    ) AS column_name
    FROM tbl t;

    分贝<> fiddle here -- 带有扩展的测试用例

    不是 将未嵌套的元素转换为 integer (就像另一个答案所暗示的那样)。
  • 数值可能不适合 integer .
  • JSON 数组(与 Postgres 数组不同)可以包含多种元素类型。所以有些数组元素可能是numeric , 但其他人 string
  • 转换所有数组元素(在左侧)会更昂贵。只需转换要替换的值(在右侧)。

  • 所以这适用于任何类型,而不仅仅是整数(JSON 数字)。例子:
    '{"values": ["abc", "22", 33]}') 

    关于sql - 从 JsonB 数组中删除数字项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61667358/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com