0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for answer.if i want select from mytable where data->>session1='xxx' and data->deviceid='yyy' how should write this?
something like this: select * from t where data#>>'{0,Session1}'='xxx' and data#>>'{0,DeviceId1}'='yyy'
1

You can use a json array index (starting from 0) as a path:

update my_table
set data = jsonb_set(data, '{0}', '{"Session1": "xxx", "DeviceId1": "yyy"}')
where id = 1
returning *;

 id |                                     data                                     
----+------------------------------------------------------------------------------
  1 | [{"Session1": "xxx", "DeviceId1": "yyy"}, {"Session2": "", "DeviceId2": ""}]
(1 row) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.