I have postgresql table with a jsonb column containing maps with strings as keys and string arrays as values. I want to aggregate all the maps into a single jsonb map. There should be no duplicate values in string array. How can I do this in postgres.
Eg:
Input: {"a": ["1", "2"]}, {"a": ["2", "3"], "b": ["5"]}
Output: {"a": ["1", "2", "3"], "b": ["5"]}
I tried ‘||’ operator but it overwrites values if there as same keys in maps.
Eg:
Input: SELECT ‘{"a": ["1", "2"]}’::jsonb || ‘{"a": ["3"], "b": ["5"]}’::jsonb;
Output: {"a": ["3"], "b": ["5"]}
2
Answers
You can use the jsonb_object_agg aggregate function to achieve this. The jsonb_object_agg function takes a set of key-value pairs and returns a JSONB object. You can use this function to aggregate all the maps into a single JSONB map by concatenating all the maps as key-value pairs. Here is an example query:
This will give you the following result:
Using
jsonb_object_agg
with a series ofcross join
s:See fiddle.