Update nested key with postgres json field in Rail

2019-07-24 03:02发布

I've been trying to update the following :

{"boxes": {"book": 2, "moving": 2}, "goods": {}}

to :

{"boxes": {"book_new": 2, "moving": 2}, "goods": {}}

without using a regular expression or doing this in ruby. but it seems it's a bit tricky. I want to add new key and then delete the old one, I'm not familiar with the syntax and I couldn't find much on the internet.

I was able to add a new element to the data but not to the nested boxes!! like that:

Update moves SET data = data::jsonb || '{"bookasas": 2}'   WHERE data ->> 'boxes' LIKE '%book%';

Any help is appreciated.

1条回答
做个烂人
2楼-- · 2019-07-24 03:42

There is no function to replace json key, so you should delete the old object and add new one:

update moves 
set data = jsonb_set(
    data::jsonb,
    array['boxes'],
    (data->'boxes')::jsonb - 'book' || jsonb_build_object('book_new', data->'boxes'->'book')
    )
where data ->> 'boxes' like '%book%'
returning *;

                         data                         
------------------------------------------------------
 {"boxes": {"moving": 2, "book_new": 2}, "goods": {}}
(1 row)
查看更多
登录 后发表回答