Skip to content
Advertisement

Expand a postgres array of JSON within a single column into multiple records

I have a table called goals where each row contains 1 goal. The data about specific metrics for the goal is stored in ARRAY of JSON called goal_metrics. Sometimes there is 1 metric, sometimes there are 0 metrics, other times there are multiple metrics. I want to extract all of the goal metrics into a new table, with 1 line per metrics and the original goal_id that metric belongs to.

This is what table1 looks like currently:

And this is what I’m trying to get to:

If it was just a regular JSON column, I could use SELECT goal_metric -> 'metrics_owner' AS metrics_owner, but because it’s an ARRAY of variable length, that won’t work. I think that I need to use JSON_TO_RECORDSET, and I’ve been experimenting with that, but I haven’t been able to achieve what I’m looking for.

Advertisement

Answer

There are different possible ways (Postgres JSON documentation):

demo:db<>fiddle


A: Using json_array_elements()

This expands every array element into one row. These expanded JSON objects can be queried for their attributes. This gives out text types. If you want them to be int types, you need a cast.


B: Using json_to_recordset()

This does the same as in (A) in one step. You just need to define the output types.


C: If you have to do this operation regularly, it might be useful to define the output type once. Then you can use it within json_populate_recordset():

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement