简体   繁体   English

如何更新 PostgreSQL 数据库中 JSONB 数组中的“键”

[英]How to UPDATE "key" in JSONB array in PostgreSQL DB

I want to update the JSONB array in PostgreSQL DB but most of the solutions I'm getting are for updating values adn NOT keys.我想更新 PostgreSQL 数据库中的 JSONB 数组,但我得到的大多数解决方案都是更新值而不是键。 My target is to change the key "SpindSpeed_Med" to "SpindleSpeed" and "RapidOveride_Med" to "RapidOverride".我的目标是将键“SpindSpeed_Med”更改为“SpindleSpeed”,将“RapidOveride_Med”更改为“RapidOverride”。

Query to make sample database:查询以创建示例数据库:

CREATE TABLE test (
    uid int,
    tooldata jsonb
);

INSERT INTO test (uid, tooldata) 
VALUES (1, '[
  {
    "Ftn": 1,
    "SpindSpeed_Med": 1234,
    "RapidOveride_Med": 100
  },
  {
    "Ftn": 2,
    "SpindSpeed_Med": 1234,
    "RapidOveride_Med": 100
  },
  {
    "Ftn": 3,
    "SpindSpeed_Med": 1234,
    "RapidOveride_Med": 100
  }]'),
(2, '[
  {
    "Ftn": 1,
    "SpindSpeed_Med": 1234,
    "RapidOveride_Med": 100
  },
  {
    "Ftn": 2,
    "SpindSpeed_Med": 1234,
    "RapidOveride_Med": 100
  },
  {
    "Ftn": 3,
    "SpindSpeed_Med": 1234,
    "RapidOveride_Med": 100
  }
]');

^ Updated for multiple rows and added uid ^更新了多行并添加了 uid

Expected result:预期结果:

[{"Ftn": 1, "SpindleSpeed": 1234, "RapidOverride": 100}, 
{"Ftn": 2, "SpindleSpeed": 1234, "RapidOverride": 100},
{"Ftn": 3, "SpindleSpeed": 1234, "RapidOverride": 100}] 

I have tried using "jsonb_set" but that only changes the value part not the key.我试过使用“jsonb_set”,但这只会改变值部分而不是键。 Also, I used a combination of "jsonb_object_keys" and "jsonb_array_elements" but that gave just keys as result and I could not put it back into the array.此外,我使用了“jsonb_object_keys”和“jsonb_array_elements”的组合,但结果只给出了键,我无法将它放回数组中。 Thanks in advance!提前致谢!

select jsonb_agg (q2) from (
  select json_agg(
    j::jsonb - 'SpindSpeed_Med' ||
    jsonb_build_object('SpindleSpeed', j->'SpindSpeed_Med')
  )
from (
    select jsonb_array_elements(tooldata) as j from jsontest
) as q) as q2 ;

First, split jsonb array to rows, remove 'SpindSpeed_Med', add 'SpindleSpeed' for each row and finally combine back to jsonb.首先,将 jsonb 数组拆分为行,删除“SpindSpeed_Med”,为每一行添加“SpindleSpeed”,最后组合回 jsonb。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM