更新数组json的数据

时间:2017-02-24 19:09:36

标签: sql postgresql jsonb

MyTable的


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

我想要更新数据并将Session1设置为等于xxx而DevicceId1等于yyy

我写了这个查询,但这没效果

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

如何在PostgreSQL中更新json数组的值?

2 个答案:

答案 0 :(得分:1)

您可以使用json数组索引(从0开始)作为路径:

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) 

答案 1 :(得分:1)

data是一个json数组,因此Session1的路径必须为{0,Session1},类似{0,DeviceId1} DeviceId1

哪个会生成更新声明:

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