简体   繁体   中英

How to update JSONB array in postgres

I have a table with following definition:

CREATE TABLE USER_CONFIGURATIONS (
  ID         BIGSERIAL PRIMARY KEY,
  DATA       JSONB
);

I have a data field that looks like this :

[
    {
        "user_id": 1,       
        "user_name": "demo_user", 
        "is_manager": 1,        
        "options": [
            {
                "phone":{
                    "home":"XXXXXXX",
                    "work":"XXXXXXX"
                },
                "address":{
                    "home":"XXXXXXX",
                    "work":"XXXXXXX"
                }
            }
        ]
    },
    ...
]

questions:

  • how to update "user_name" ?
  • how to update "options->phone->home" ?

    UPDATE USER_CONFIGURATIONS SET DATA = jsonb_set(...) WHERE ...user_id=1;

postgres 9.6 version. i tried with jsonb_set() but not wokring

https://www.db-fiddle.com/f/4ZYZiuJr4QgfNkzyTCeT1X/1

just run it twice:

update USER_CONFIGURATIONS
set data =  
jsonb_set(
  jsonb_set(
    data,'{0,"user_name"}','"blah"'
  ), '{0,"options",0,"phone","home"}','999999'
)
where id =1
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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