【问题标题】:Insert jsonb object to other jsonb by key按键插入jsonb对象到其他jsonb
【发布时间】:2021-10-09 23:06:13
【问题描述】:

我将以下数据定义为 jsonb。

{
   "rules":[
      {
         "group":"identifier",
         "logic":"=",
         "value":"token",
         "fieldId":"vfde_0010"
      },
      {
         "rules":[
            {
               "group":"identifier",
               "logic":"=",
               "value":"111",
               "fieldId":"vfde_0011"
            }
         ],
         "condition":"and"
      }
   ],
   "version":"v_0021",
   "category":"mobile",
   "condition":"and",
   "createdAt":"2020-01-17T03:13:42Z"
}

然后我想将这个新的 jsonb 数据包含在上面。

{
   "rules":[
      {
         "group":"identifier",
         "logic":"=",
         "value":"msisdn-sha2",
         "fieldId":"vfde_0010"
      }
   ],
   "condition":"and"
}

结果会是这样。

{
   "rules":[
      {
         "group":"identifier",
         "logic":"=",
         "value":"token",
         "fieldId":"vfde_0010"
      },
      {
         "rules":[
            {
               "group":"identifier",
               "logic":"=",
               "value":"111",
               "fieldId":"vfde_0011"
            }
         ],
         "condition":"and"
      },
      {
         "rules":[
            {
               "group":"identifier",
               "logic":"=",
               "value":"msisdn-sha2",
               "fieldId":"vfde_0010"
            }
         ],
         "condition":"and"
      }
   ],
   "version":"v_0021",
   "category":"mobile",
   "condition":"and",
   "createdAt":"2020-01-17T03:13:42Z"
}

我尝试使用 ||运算符,但我对结果感到困惑:(data->>'rules' || new)。

[
   {
      "group":"identifier",
      "logic":"=",
      "value":"token",
      "fieldId":"vfde_0010"
   },
   {
      "rules":[
         {
            "group":"identifier",
            "logic":"=",
            "value":"111",
            "fieldId":"vfde_0011"
         }
      ],
      "condition":"and"
   }
]{
   "rules":[
      {
         "group":"identifier",
         "logic":"=",
         "value":"msisdn-sha2",
         "fieldId":"vfde_0010"
      }
   ],
   "condition":"and"
}

是我使用了错误的运算符还是有其他正确的方法可以做到这一点?

我使用 PostgreSQL 12.1

【问题讨论】:

    标签: postgresql jsonb


    【解决方案1】:

    您需要使用jsonb_insert

    试试:

    jsonb_insert(data, '{ rules, 2 }', (your new value))
    

    另见jsonb documentation

    披露:我为EnterpriseDB (EDB)工作

    【讨论】:

    • 谢谢,我想接受你的回答,但我必须等待 4 分钟。工作查询:jsonb_insert(data, '{rules,0}', new)
    猜你喜欢
    • 2021-05-04
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    相关资源
    最近更新 更多