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

编程入门 行业动态 更新时间:2024-10-27 04:32:20
本文介绍了在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字段更新嵌套键

本文发布于:2023-10-16 10:44:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   字段   Rails   postgres   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!