gpt4 book ai didi

json - 将jsonb键值转换为键值数组

转载 作者:行者123 更新时间:2023-11-29 12:23:57 24 4
gpt4 key购买 nike

对于笔记应用程序,我的 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 部分中运行类似子查询的方法。

最佳答案

使用函数jsonb_build_array():

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

Working example in rextester.

关于json - 将jsonb键值转换为键值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com