简体   繁体   中英

Jsonb array of objects update

So this is my jsonb array of objects. Column is called bids in my db.

bids column

 [
      {
        "id": "1",
        "size": "5.5Y",
        "price": 180
      },
      {
        "id": "f0d1d36a-f6af-409e-968e-54c1dc104566",
        "size": "6.5Y",
        "price": 22
      }
    ]

I want to update price property by the ID of an element for ex. "f0d1d36a-f6af-409e-968e-54c1dc104566", so the price would change from 22 to 150 IN ROW WHICH CONTAINS ELEMENT WITH DESIRED ID IN THE COLUMN. How can I do that?

create table json_update (id integer, json_fld jsonb);
insert into json_update values (1, '[
      {
        "id": "1",
        "size": "5.5Y",
        "price": 180
      },
      {
        "id": "f0d1d36a-f6af-409e-968e-54c1dc104566",
        "size": "6.5Y",
        "price": 22
      }
    ]'
)
;


UPDATE
    json_update
SET
    json_fld = jsonb_set(json_fld, ARRAY[(idx)::text, 'price'::text], '150'::jsonb)
FROM (
    SELECT
        (row_number() OVER (ORDER BY t.a ->> 'id') - 1) AS idx,
        t.a
    FROM (
        SELECT
            jsonb_array_elements(json_fld)
        FROM
            json_update) AS t (a)) AS i
WHERE
    i.a ->> 'id' = 'f0d1d36a-f6af-409e-968e-54c1dc104566';

select * from json_update ;
 id |                                                         json_fld                                                          
----+---------------------------------------------------------------------------------------------------------------------------
  1 | [{"id": "1", "size": "5.5Y", "price": 180}, {"id": "f0d1d36a-f6af-409e-968e-54c1dc104566", "size": "6.5Y", "price": 150}]


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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