且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将JSON对象推送到JSONB列中的嵌套数组

更新时间:2023-02-05 14:41:28

jsonb_set()的窍门是,它修改了jsonb对象的一部分,但返回了整个对象.因此,您向其传递了列的当前值和要修改的路径(此处为字符串数组,此处为页面"),然后采用现有的数组(my_column->'pages')并将新对象附加到|| . jsonb对象的所有其他部分保持不变.您正在为该列有效地分配一个全新的对象,但这无关紧要,因为UPDATE无论如何都会向物理表中写入新行.

The trick to jsonb_set() is that it modifies part of a jsonb object, but it returns the entire object. So you pass it the current value of the column and the path you want to modify ("pages" here, as a string array), then you take the existing array (my_column->'pages') and append || the new object to it. All other parts of the jsonb object remain as they were. You are effectively assigning a completely new object to the column but that is irrelevant because an UPDATE writes a new row to the physical table anyway.

UPDATE my_table
SET my_column = jsonb_set(my_column, '{pages}', my_column->'pages' || new_json, true);

在此处设置为true的可选create_missing参数(如果尚不存在)将添加"pages"对象.

The optional create_missing parameter set to true here adds the "pages" object if it does not already exist.