json - 在 postgresql 中更新嵌套 json 中的值
问题描述
我正在处理包含具有这种结构的 jsons 的 postgresql 表的列:
{
"id": "a",
"user_id": " e",
"event_id": 1,
"last_snooze_timestamp": "2021-02-25T13:45:26.000000+00:00",
"number_of_participants": 3,
"participants": {
"743d774d-835a-436a-b7e8-0acb6af9f683":{
"nome": "abc",
"cognome": "abc",
"pdfURL": "indirizzoPDF",
"type": "Booker",
"access": null
},
"453f0613-e1fb-41ef-bf35-5e0520ed8995": {
"nome": "cde",
"cognome": "cde",
"pdfURL": "indirizzoPDF",
"type": "Minor",
"access": null
}
}
}
我的任务是用当前时间戳更新键“访问”的值,当且仅当前一个值为空时。我的函数显然得到了 id(“743d774d-835a-436a-b7e8-0acb6af9f683”、“453f0613-e1fb-41ef-bf35-5e0520ed8995”等)作为输入,我能够到达表格中有趣的行。
我试过这种语法:
SELECT jsonb_set(json_to_modify, 'path', jsonb '{"key":value}')
我正在考虑用 覆盖
{"access": null}
,{"access": timestamp}
但是:- 我无法正确指向
participants
jsonb, - 覆盖整个键/值对感觉不雅且有些危险。
- 我无法正确指向
我在此页面中找到的语法:https ://dev.to/deepika_banoth/how-to-use-jsonbset-function-in-postgresql-35eo
在第 2 点:
UPDATE "json" SET "participants"=jsonb_set("participants"::jsonb, '{access}', '"timestamp"' WHERE "details"::json->>'id'='"743d774d-835a-436a-b7e8-0acb6af9f683"'
但仍然无法使其工作,因为我无法正确指向参与者 json。
- 其他无意义的语法。
我将感谢任何想帮助我或给我有关如何处理问题的线索的人。
解决方案
您可以使用jsonb_set
,只需在参数中使用所需属性的路径path
:
UPDATE ...
SET jsonb_col = jsonb_set(
jsonb_col,
'{participants,743d774d-835a-436a-b7e8-0acb6af9f683,access}',
JSONB '"2021-09-01 12:00:00"'
)
请注意不要使用 NULL 代替时间戳,因为这样的结果jsonb_set
也是 NULL。
请注意,修改数据库中的大型 JSON 效率不高,因为它总是会写入整个值。
推荐阅读
- pytorch - CUDA 错误 59:触发了设备端断言
- python - 用于模板匹配的 Python OpenCV
- python - PRAW:你是怎么得到你的提交链接的?
- c# - 您如何通过共同属性将两个自定义对象相互比较?
- php - 延迟睡眠时遇到问题
- nativescript - 获取 ios [Nativescript] 的新构建错误
- c# - 在 C# 中调用自身内部的方法
- python - mt19937 prng 究竟如何用于 python 随机模块函数?
- postgresql - 编译 Postgresql 后 12 hstore 扩展未找到
- javascript - 在 node.js 6.11.0 中处理异步函数