Update or create nested jsonb value using single update command

后端 未结 2 1886
时光说笑
时光说笑 2021-02-05 17:56

Let us say I have [in Postgres 9.6] a JSONB column named xyz. In an update, I want to set the .foo.bar key of this column to {\"

2条回答
  •  借酒劲吻你
    2021-02-05 18:07

    You can just use || to concatenate. It will overwrite or add any json value.

    SELECT '{}'::jsonb || '{"foo":"bar"}'::jsonb
    UPDATE tablename SET jdoc = jdoc || '{"foo":"bar"}'::jsonb
    

    It's that easy. I rarely use the functions in my software.

    In the case of merging:

    create or replace function jsonb_merge(orig jsonb, delta jsonb)
    returns jsonb language sql as $$
        select
            jsonb_object_agg(
                coalesce(keyOrig, keyDelta),
                case
                    when valOrig isnull then valDelta
                    when valDelta isnull then valOrig
                    when (jsonb_typeof(valOrig) <> 'object' or jsonb_typeof(valDelta) <> 'object') then valDelta
                    else jsonb_merge(valOrig, valDelta)
                end
            )
        from jsonb_each(orig) e1(keyOrig, valOrig)
        full join jsonb_each(delta) e2(keyDelta, valDelta) on keyOrig = keyDelta
    $$;
    

提交回复
热议问题