首页 > 解决方案 > 在 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”等)作为输入,我能够到达表格中有趣的行。

我试过这种语法:

  1. SELECT jsonb_set(json_to_modify, 'path', jsonb '{"key":value}')

    我正在考虑用 覆盖{"access": null}{"access": timestamp}但是:

    • 我无法正确指向participantsjsonb,
    • 覆盖整个键/值对感觉不雅且有些危险。
  2. 我在此页面中找到的语法: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。

    • 其他无意义的语法。

我将感谢任何想帮助我或给我有关如何处理问题的线索的人。

标签: jsonpostgresql

解决方案


您可以使用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 效率不高,因为它总是会写入整个值。


推荐阅读