在PostgreSQL中,如何使用JSONB将列表添加到现有JSON对象

问题描述 投票:0回答:1

这段代码:

do
$j$
declare arr text[]; i int; num text; obj jsonb; jb_arr jsonb[];

begin

        jb_arr = array_append(jb_arr, jsonb_build_object('k', 'acg', 'v', 'val'));
        jb_arr = array_append(jb_arr, jsonb_build_object('k', 'xyz', 'v', 'xxx'));

        obj = (select '{ "cmds":[]}'::jsonb);

        RAISE NOTICE '%', to_jsonb(jb_arr); 

        RAISE NOTICE '%', obj;

end;
$j$

输出:

[{"k": "acg", "v": "val"}, {"k": "xyz", "v": "xxx"}]
{"cmds": []}

我如何合并这两个,以便我最终得到这个:

{"cmds": [{"k": "acg", "v": "val"}, {"k": "xyz", "v": "xxx"}]}

谢谢!

json jsonb postgresql-9.6
1个回答
0
投票

这是如何:(选择json_build_object('cmds',jb_arr));

© www.soinside.com 2019 - 2024. All rights reserved.