Search code examples
sqlpostgresqljsonb

Converting jsonb to regular array in postgres


I have the following table:

"Id"|                  "Data"
====+================================================
1   | { "emp": [ 
    |            {"id": "a1", "otherdata": "other"}, 
    |            {"id": "a2", "otherdata": "other"} 
    |          ]
    | }
----+------------------------------------------------
2   | { "emp": [ 
    |            {"id": "b1", "otherdata": "other"}, 
    |            {"id": "b2", "otherdata": "other"} 
    |          ]
    | }
-----------------------------------------------------

Where "Data" is jsonb.

I need to create a temporary table of this type:

"Id"| "Emp"
====+=============
1   | {"a1", "a2"}
----+-------------
2   | {"b1", "b2"}

How can I do this?


Solution

  • Use jsonb_to_recordset to extract the array values to rows, group them, then back to an array using array_to_json.

    SELECT a.id, array_to_json(array_agg(b.id)) AS emp
    FROM mytable a
    CROSS JOIN jsonb_to_recordset(a.data->'emp') AS b(id text)
    GROUP BY a.id;
    

    See SQL Fiddle