How do I modify fields inside the new PostgreSQL JSON datatype?

前端 未结 21 1948
孤独总比滥情好
孤独总比滥情好 2020-11-22 15:37

With postgresql 9.3 I can SELECT specific fields of a JSON data type, but how do you modify them using UPDATE? I can\'t find any examples of this in the postgresql documenta

相关标签:
21条回答
  • 2020-11-22 16:38

    This worked for me, when trying to update a string type field.

    UPDATE table_name 
    SET body = jsonb_set(body, '{some_key}', to_json('value'::text)::jsonb);
    

    Hope it helps someone else out!

    Assuming the table table_name has a jsonb column named body and you want to change body.some_key = 'value'

    0 讨论(0)
  • 2020-11-22 16:39

    With Postgresql 9.5 it can be done by following-

    UPDATE test
    SET data = data - 'a' || '{"a":5}'
    WHERE data->>'b' = '2';
    

    OR

    UPDATE test
    SET data = jsonb_set(data, '{a}', '5'::jsonb);
    

    Somebody asked how to update many fields in jsonb value at once. Suppose we create a table:

    CREATE TABLE testjsonb ( id SERIAL PRIMARY KEY, object JSONB );
    

    Then we INSERT a experimental row:

    INSERT INTO testjsonb
    VALUES (DEFAULT, '{"a":"one", "b":"two", "c":{"c1":"see1","c2":"see2","c3":"see3"}}');
    

    Then we UPDATE the row:

    UPDATE testjsonb SET object = object - 'b' || '{"a":1,"d":4}';
    

    Which does the following:

    1. Updates the a field
    2. Removes the b field
    3. Add the d field

    Selecting the data:

    SELECT jsonb_pretty(object) FROM testjsonb;
    

    Will result in:

          jsonb_pretty
    -------------------------
     {                      +
         "a": 1,            +
         "c": {             +
             "c1": "see1",  +
             "c2": "see2",  +
             "c3": "see3",  +
         },                 +
         "d": 4             +
     }
    (1 row)
    

    To update field inside, Dont use the concat operator ||. Use jsonb_set instead. Which is not simple:

    UPDATE testjsonb SET object =
    jsonb_set(jsonb_set(object, '{c,c1}','"seeme"'),'{c,c2}','"seehim"');
    

    Using the concat operator for {c,c1} for example:

    UPDATE testjsonb SET object = object || '{"c":{"c1":"seedoctor"}}';
    

    Will remove {c,c2} and {c,c3}.

    For more power, seek power at postgresql json functions documentation. One might be interested in the #- operator, jsonb_set function and also jsonb_insert function.

    0 讨论(0)
  • 2020-11-22 16:40

    UPDATE table_name SET attrs = jsonb_set(cast(attrs as jsonb), '{key}', '"new_value"', true) WHERE id = 'some_id';

    This what worked for me, attrs is a json type field. first cast to jsonb then update.

    or

    UPDATE table_name SET attrs = jsonb_set(cast(attrs as jsonb), '{key}', '"new_value"', true) WHERE attrs->>key = 'old_value';

    0 讨论(0)
提交回复
热议问题