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

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

    I wrote small function for myself that works recursively in Postgres 9.4. Here is the function (I hope it works well for you):

    CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
    RETURNS JSONB AS $$
    DECLARE
        result JSONB;
        v RECORD;
    BEGIN
        IF jsonb_typeof(val2) = 'null'
        THEN 
            RETURN val1;
        END IF;
    
        result = val1;
    
        FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP
    
            IF jsonb_typeof(val2->v.key) = 'object'
                THEN
                    result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
                ELSE
                    result = result || jsonb_build_object(v.key, v.value);
            END IF;
        END LOOP;
    
        RETURN result;
    END;
    $$ LANGUAGE plpgsql;
    

    Here is sample use:

    select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
                                jsonb_update                             
    ---------------------------------------------------------------------
     {"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
    (1 row)
    

    As you can see it analyze deep down and update/add values where needed.

提交回复
热议问题