更新jsonb对象数组中的键值

时间:2018-06-06 00:53:14

标签: arrays postgresql jsonb postgresql-9.6

我有下表company,其中jsonb列名为log: -

|code | log
-----------------------------------------------------------------------------
|K50  | [{"date": "2002-02-06", "type": "Chg Name", "oldvalue": "TEH   "},
         {"date": "2003-08-26", "type": "Chg Name", "oldvalue": "TEOA   "}]
|C44  | [{"date": "2003-05-07", "type": "Chg Name", "oldvalue": "CDE   "}]

如何修剪oldvalue中的尾随空白?

2 个答案:

答案 0 :(得分:0)

在postgreSQL中,jsonb数据类型用于存储json作为其接收。如果你想更新其中的任何值,你需要转换代码中的数据,然后才有资格存储在DB中。这是一个好的在这种情况下,应该从代码本身处理尾随空格。如果你想明确更新,那也是可能的。

PFB链接。

How to perform update operations on columns of type JSONB in Postgres 9.4

答案 1 :(得分:0)

你可以混合使用jsonb functions and operators

UPDATE company c
SET    log = sub.log2
FROM  (
   SELECT *
   FROM   company c
   CROSS  JOIN LATERAL (
      SELECT jsonb_agg(jsonb_set(l, '{oldvalue}', to_jsonb(rtrim(l->>'oldvalue')))) AS log2
      FROM   jsonb_array_elements(c.log) l
      ) sub
   WHERE  jsonb_typeof(log) = 'array'  -- exclude NULL and non-arrays
   ) sub
WHERE  c.code =  sub.code   -- assuming code is unique
AND    c.log  <> sub.log2;  -- only where column actually changed.

SQL Fiddle.