【问题标题】:Update a value in a nested json in postgresql在 postgresql 中更新嵌套 json 中的值
【发布时间】:2021-10-30 19:43:52
【问题描述】:

我正在处理包含具有这种结构的 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
        }
    }
}

我的任务是用当前时间戳更新键“access”的值,当且仅当前一个值为空时。我的功能显然得到了 id ("743d774d-835a-436a-b7e8-0acb6af9f683", "453f0613-e1fb-41ef-bf35-5e0520ed8995", etc) 作为输入,我可以访问表格中有趣的行。

我试过这种语法:

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

    我曾考虑用{"access": timestamp} 覆盖{"access": null},但是:

    • 我无法正确指向participants jsonb,
    • 覆盖整个键/值对感觉不雅且有些危险。
  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。

    • 其他无意义的语法。

如果有人愿意帮助我或提供有关如何处理问题的线索,我将不胜感激。

【问题讨论】:

    标签: json postgresql


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多