postgresql-9.5 - 无法在 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"
}]
}
解决方案
你需要使用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;
推荐阅读
- ssas - 在 Azure 分析服务上编写 MDX / DAX,并使用 ADF 将数据复制到 azure 数据仓库
- android - 向下滚动到新帖子时单击不工作
- vba - 使用 excel/vba 堆叠数据
- mysql - 计算数字的出现次数并在存储过程中使用 case 表达式
- python - Python - TypeError:列表索引必须是整数或切片,而不是尝试设置 cookie 时的 dict
- amazon-web-services - AWS:私有子网的 VPC 接口终端节点
- javascript - npm install 的问题 - 无法解决依赖关系。有解决办法吗?
- python - 使用 python 在 docker running 容器上运行 exec
- php - 在 PHP 中导出 CSV 文件时如何避免添加信息
- firebase - 如何将 Firestore 子集合导出到 Google 表格?