简体   繁体   English

更新postgres jsonb列

[英]updating postgres jsonb column

I have below json string in my table column which is of type jsonb, 我的表列中有jsonb类型的json字符串,

{
    "abc": 1,
    "def": 2
}

i want to remove the "abc" key from it and insert "mno" with some default value. 我想从中删除“ abc”键,并使用一些默认值插入“ mno”。 i followed the below approcach for it. 我遵循以下方法。

UPDATE books SET books_desc = books_desc - 'abc';
UPDATE books SET books_desc = jsonb_set(books_desc, '{mno}', '5');

and it works. 而且有效。

Now i have another table with json as below, 现在我有另一个带有json的表,如下所示,

{
    "a": {
        "abc": 1,
        "def": 2
    },
    "b": {
        "abc": 1,
        "def": 2
    }
}

Even in this json, i want to do the same thing. 即使在这个json中,我也想做同样的事情。 take out "abc" and introduce "mno" with some default value. 取出“ abc”并引入一些默认值的“ mno”。 Please help me to achieve this. 请帮助我实现这一目标。

The keys "a" and "b" are dynamic and can change. 键“ a”和“ b”是动态的,可以更改。 But the values for "a" and "b" will always have same keys but values may change. 但是“ a”和“ b”的值将始终具有相同的键,但值可能会更改。 I need a generic logic. 我需要一个通用逻辑。

Requirement 2: 要求2:

abc:true should get converted to xyz:1. abc:true应该转换为xyz:1。

abc:false should get converted to xyz:0. abc:false应该转换为xyz:0。

demo:db<>fiddle demo:db <>小提琴

Because of a possible variety of your JSON keys it might be complicated to generate a common query. 由于您的JSON键可能多种多样,因此生成通用查询可能会很复杂。 This is because you need to give the path within the json_set() function. 这是因为您需要在json_set()函数中提供路径。 But without actual values it would be hard. 但是如果没有实际价值,那就很难了。

A simple work-around is using the regexp_replace() function on the text representation of the JSON string to replace the relevant objects. 一个简单的解决方法是在JSON字符串的文本表示regexp_replace()使用regexp_replace()函数来替换相关对象。

UPDATE my_table
SET my_data = 
    regexp_replace(my_data::text, '"abc"\s*:\s*\d+', '"mno":5', 'g')::jsonb

For added requirement 2: 对于附加要求2:

I wrote the below query based on already given solution: 我根据已经给出的解决方案编写了以下查询:

UPDATE books
SET book_info = 
    regexp_replace(book_info::text, '"abc"\s*:\s*true', '"xyz":1', 'g')::jsonb; 

UPDATE books
SET book_info = 
    regexp_replace(book_info::text, '"abc"\s*:\s*false', '"xyz":0', 'g')::jsonb;   

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

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