简体   繁体   English

在Rails中使用postgres json字段更新嵌套键

[英]Update nested key with postgres json field in Rails

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. 而不使用正则表达式或在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. 任何帮助表示赞赏。

There is no function to replace json key, so you should delete the old object and add new one: 没有替换json键的功能,因此您应该删除旧对象并添加新对象:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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