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

Can't add (correct) item in array in jsonb column

meta - 列类型 jsonb

Json 更新前:

{
    "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, '{comments}', '[{ "first_item": "hello"}]')
             end;