I have a following jsonb data inside the jsonb_col
{
"a": { "keyA": 1 , "keyB": 2 },
"b": { "keyA": 1 , "keyB": 3 },
"c": { "keyA": 1 , "keyC": 4 }
}
I want to duplicate the key pair for each entry given a new key and a old key
For example: newKey
and keyB
,
{
"a": { "keyA": 1 , "keyB": 2, "newKey": 2 },
"b": { "keyA": 1 , "keyB": 3, "newKey": 3 },
"c": { "keyA": 1 , "keyC": 4 } // do nothing if the object doesn't have the given key.
}
I know I can do v || '{ "newKey": "value" }'
to merge the data, but I actually don’t know how to dynamically grab the value from keyB
That’s my current non-working attempt, since v
is invalid as expect
UPDATE the_table
SET jsonb_col = (
SELECT jsonb_object_agg(
k,
v || '{ "newKey": v -> "keyB" }'
)
FROM jsonb_each(jsonb_col) AS dt(k,v)
);
Not sure how to properly use v
token to construct the entry and skip the empty case.
The playground for this problem: https://dbfiddle.uk/qp29LGAV