本文介绍了在Rails中使用postgres json字段更新嵌套键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试更新以下内容:
I've been trying to update the following :
{"boxes": {"book": 2, "moving": 2}, "goods": {}}至:
{"boxes": {"book_new": 2, "moving": 2}, "goods": {}},无需使用正则表达式或在ruby中执行此操作.但似乎有点棘手. 我想添加新密钥,然后删除旧密钥,我对语法不熟悉,在互联网上找不到很多密钥.
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%';感谢您的帮助.
推荐答案没有替换json键的功能,因此您应该删除旧对象并添加新对象:
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)更多推荐
在Rails中使用postgres json字段更新嵌套键
发布评论