首页 > 解决方案 > 无法在 jsonb 列的数组中添加(正确)项目

问题描述

元 - 列类型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"
    }]
  }

标签: postgresql-9.5

解决方案


你需要使用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;

推荐阅读