Search code examples
sqlpostgresqljsonb

Update data of array json


MyTable


id |  data
___________
1  |[{"Session1": "", "DeviceId1": ""}, {"Session2": "", "DeviceId2": ""}]

I want update data and set Session1 equal to xxx and DevicceId1 eaqual to yyy

I write this query but this not worked

update MyTable data=jsonb_set(data, '{Session1}', 'xxx',true)

How can update value of array of json in PostgreSQL?


Solution

  • data is a json array, so the path to Session1 needs to be {0,Session1}, similarly {0,DeviceId1} for DeviceId1

    Which would make the update statement:

    UPDATE "MyTable"
    SET "data" = jsonb_set(jsonb_set(data, '{0,Session1}', '"xxx"', true), '{0,DeviceId1}', '"yyy"', true)
    WHERE id = 1