如何在单个更新查询中更新 json 字段中的多个嵌套键?

How to update multiple nested keys in a json field in single update query?

我正在尝试编写一个函数来更新 table(称为 [=16])中的 json(不是 jsonb)字段(称为 settings) =]).

我的 json object 看起来像这样(但是它可能没有任何嵌套级别的某些键):

{
  "audiences": ["val1", "val2"],
  "inviteNumber": "123",
  "workExperience": [
    {
      "company": {
        "name": "Ace",
        "industry": "Accounting",
        "revenues": "1M-10M",
        "size": "1-10"
      },
      "title": "Product",
      "startDate": {
        "month": 1,
        "year": 2018
      }
    }
  ],
  "notifications": {
    "emailNotifications": true
  },
  "jobFunction": "Research & Development",
  "phoneNumber": "2134447777",
  "areasOfInterest": {
    "Recruiting and Staffing": true
  }
}

我需要能够更新“workExperience”数组中第 0 个元素的“标题”和“名称”字段。

我目前拥有的是:

create or replace function my_function()
returns trigger language plpgsql as $$
declare
    companyName character varying(255);
begin
    select company.name into companyName from company where id = new.companyid;

    update "user" set
        email = new.email,
        "settings" = jsonb_set(
            "settings"::jsonb,
            '{workExperience,0}'::TEXT[],
            format(
                '{"company": {"name": %s}, "title": %s}',
                '"' || companyName || '"', '"' || new.title || '"'
            )::jsonb
        )
    where id = new.userid;
    
    return new;
end $$;

但是上面的实现重写了 while workExperience object 删除了 companytitle.

以外的键

我已经尝试查看 this answer on SO,但仍然无法正确实施更新。

我发现问题出在 jsonb_set 的工作方式上,它完全按照我的要求执行:将“workExperience”数组的第 0 个元素设置为我在 object 中定义的 format函数。 好像我需要在另一个里面使用多个 jsonb_set,但我想不出正确的方法。


如何在不从 object 中删除其他键的情况下正确更新我的 json 字段?

jsonb_set() returns 修改后的 JSON 值。

您可以先嵌套调用并更改公司名称,然后将其结果用作另一个 jsonb_set() 的输入。

"settings" = jsonb_set(jsonb_set("settings"::jsonb, '{workExperience,0,company,name}', to_jsonb(companyname)), 
                       '{workExperience,0,title}', to_jsonb(new.title)
                      )