无法在jsonb列的数组中添加正确项目

问题描述

元-列类型 jsonb

更新前的杰森:

{
    "state": "order.cart_finalization","comments": [{
        "first_item": "hello"
    }]
}

我需要向数组(注释)添加新项目。

新数组项是:

{ "second_item": "hello2"}

我尝试这个:

 UPDATE copy_shop_order SET Meta = (
    CASE
        WHEN Meta #>>'{comments}' IS NULL THEN jsonb_set(Meta,'{comments}','[{ "first_item": "hello"}]')
        ELSE Meta #>'{comments}' || '{ "second_item": "hello2"}'
    END
) WHERE id = 100;

但是结果是:

[
    {
        "first_item": "hello"
    },{
        "second_item": "hello2"
    }
]

但是我需要这个:

  {
    "state": "order.cart_finalization","comments": [{
        "first_item": "hello"
    },{
        "second_item": "hello2"
    }]
  }

解决方法

您需要使用jsonb_set()

update copy_shop_order 
  SET meta = case 
               when meta ? 'comments' then jsonb_set(meta,'{comments}',meta -> 'comments' || '{"second_item": "hello2"}')
               else jsonb_set(meta,'[{ "first_item": "hello"}]')
             end;