CREATE OR REPLACE FUNCTION jsonb_diff_val(val1 JSONB, val2 JSONB) RETURNS JSONB AS $$
DECLARE
    result JSONB;
    difference jsonb;
    v RECORD;
BEGIN
    result = val1;
    FOR v IN SELECT * FROM jsonb_each(val2) LOOP
            IF result -> v.key is not null
            THEN
                if(jsonb_typeof(v.value) ='object') then
                    difference = jsonb_diff_val(result->v.key, v.value);

                    if (difference = '{}'::jsonb) then
                        result = result - v.key;
                    else
                        result = jsonb_set(result, array[v.key], difference);
                    end if;
                else
                    if (result -> v.key = v.value) then
                        result = result - v.key;
                    else continue;
                    end if;
                end if;
            ELSE
                result = result || jsonb_build_object(v.key, null);
            END IF;
        END LOOP;
    RETURN result;
END;
$$ LANGUAGE plpgsql;