将jsonb键值转换为键值数组

时间:2018-08-25 11:45:24

标签: json postgresql jsonb

对于记笔记应用程序,我现在在PostgreSQL模式中具有以下json文档:

postgres=# select id, data from notes where id=107;
 id  |                                           data                                           
-----+-----------------------------------------------------------------    
 107 | {"tag": "sample tag", "title": "sample title", "content": "sample title\n\nsample text"}

为了将来能够使用多个标签,我想将以上数据库中的每个现有条目都转换为如下所示的数组:"tag": ["sample tag"]

我做了一些研究,通过玩耍,我变得更接近了:

UPDATE notes SET data = jsonb_set(data, '{tag}', $$["sample tag", "xyz"]$$);

实际上将行从"tag": "sample tag"更新为"tag": ["sample tag", "xyz"],但是我希望它能在所有带有现有标记的条目中动态运行。我找不到在jsonb_set部分中运行子查询之类的方法。

1 个答案:

答案 0 :(得分:0)

使用功能jsonb_build_array():

update notes
set data = jsonb_set(data, '{tag}', jsonb_build_array(data->'tag'));

Working example in rextester.

相关问题