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

前端 未结 21 2218
孤独总比滥情好
孤独总比滥情好 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:14

    what do you think about this solution ?

    It will add the new value or update an existing one.

    Edit: edited to make it work with null and empty object

    Edit2: edited to make it work with object in the object...

    create or replace function updateJsonb(object1 json, object2 json)
    returns jsonb
    language plpgsql
    as
    $$
    declare
        result jsonb;
        tempObj1 text;
        tempObj2 text;
    
    begin
        tempObj1 = substr(object1::text, 2, length(object1::text) - 2); --remove the first { and last }
        tempObj2 = substr(object2::text, 2, length(object2::text) - 2); --remove the first { and last }
    
        IF object1::text != '{}' and object1::text != 'null' and object1::text != '[]' THEN
            result = ('{' || tempObj1 || ',' || tempObj2 || '}')::jsonb;
        ELSE
            result = ('{' || tempObj2 || '}')::jsonb;
        END IF;
        return result;
    end;
    $$;
    

    usage:

    update table_name
    set data = updatejsonb(data, '{"test": "ok"}'::json)
    

提交回复
热议问题