【问题标题】:How to append to a nested array in a JSONB column如何追加到 JSONB 列中的嵌套数组
【发布时间】:2020-04-11 08:49:46
【问题描述】:

其他地方接受的答案 (How to push a JSON object to a nested array in a JSONB column) 不适用于我的情况。

我想将一个字符串附加到一个非空 JSONB 列中的嵌套数组。如果数组不存在,我想创建它(并添加我的字符​​串)。更新前列的内容将是一个对象{}(即不是数组)。

以下只是导致“数据”列中的空值违反非空约束约束错误:

update md_ticker
SET data = jsonb_set(data, '{labels}', data -> 'labels' || '"some string"', true)
where id = 74650534

【问题讨论】:

    标签: arrays json postgresql jsonb


    【解决方案1】:

    使用case检查labels数组是否存在:

    update md_ticker
    set data = case 
        when data ? 'labels' then 
            jsonb_set(data, '{labels}', data -> 'labels' || '"some string"', true)
        else
            data || '{"labels": ["some string"]}'
        end
    where id = 74650534
    

    【讨论】:

      猜你喜欢
      • 2018-04-26
      • 2016-12-20
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多