sql - 向 Json 数组添加新元素

标签 sql arrays json postgresql jsonb

我想在 json 下面的 a3 中添加一个新的数组元素:

{
    "a1": "e1",
    "a2": {
        "b1": "y1",
        "b2": "y2"
    },
    "a3": [{
            "arr1": "1"
        },
        {
            "arr2": "2"
        }
    ]
}

所以我希望上面的 json 是这样的:

{
    "a1": "e1",
    "a2": {
        "b1": "y1",
        "b2": "y2"
    },
    "a3": [{
            "arr1": "1"
        },
        {
            "arr2": "2"
        },
        {
            "arr3": "3"
        }
    ]
}

我可以使用以下命令添加新元素。但是当涉及到数组时,我找不到添加新元素的方法。

SELECT jsonb_set('{ "a1": "e1", "a2": { "b1": "y1", "b2": "y2" }, "a3": [{ "arr1": "1" }, { "arr2": "2" }] }'::jsonb,
'{a2,b3}', 
'"4"');

我应该使用什么命令将 { "arr3": "3"} 添加到 a3?

编辑:如果 arr3 已经存在,命令应该改变它的值。不应添加重复的 {"arr3":"3"}。

最佳答案

对数组使用连接运算符||:

with my_data(json_data) as (
values
    ('{ "a1": "e1", "a2": { "b1": "y1", "b2": "y2" }, "a3": [{ "arr1": "1" }, { "arr2": "2" }] }'::jsonb)
)

select jsonb_set(json_data, '{a3}', json_data->'a3' || '{"arr3": "3"}')
from my_data;

                                             jsonb_set                                             
---------------------------------------------------------------------------------------------------
 {"a1": "e1", "a2": {"b1": "y1", "b2": "y2"}, "a3": [{"arr1": "1"}, {"arr2": "2"}, {"arr3": "3"}]}
(1 row)

检查键是否存在于嵌套数组中有点复杂。您应该使用 jsonb_array_elements() 取消嵌套数组来执行此操作:

with my_data(json_data) as (
values
    ('{ "a1": "e1", "a2": { "b1": "y1", "b2": "y2" }, "a3": [{ "arr1": "1" }, { "arr2": "2" }] }'::jsonb)
)

select 
    case when already_exists then json_data
    else jsonb_set(json_data, '{a3}', json_data->'a3' || '{"arr3": "3"}')
    end as json_data
from (
    select json_data, bool_or(value ? 'arr3') as already_exists
    from my_data
    cross join jsonb_array_elements(json_data->'a3')
    group by 1
    ) s

关于sql - 向 Json 数组添加新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54905672/

相关文章:

sql-server,SQL 查询中的 IF 语句

java.lang.ClassNotFoundException 在第一次调用其余服务时

jquery - Jackson 无法读取文档 : Unrecognized token 'contactForm' : was expecting ('true' , 'false' 或 'null' )

javascript - 使用 JSON 显示 html 链接

arrays - 移动窗口的最小值/最大值能否在 O(N) 内实现?

sql - 在SQL中将两列数据合并为一列?

sql - 合并两个 View

c# - Linq 到 SQL : delete record with generic type method

javascript使用for循环从多个字符串中删除字符

python - 这在 python : flat_array = sum( array_2d , [ ] 中如何工作)