0

I have the following data in a Postgres table that I need to flatten out:

data
===============================================================================================
{"Exterior Lights" :["Headlights - Forward Adaptive","Headlights - Laser","Headlights - LED"]}
{"Generic" : ["Launch Control"]} 
{"Mirror" :["Blind Spot Assistant","Door Mirrors - Integrated LED"]}
{"Safety" :["Tyre Pressure Monitoring", "ABS"]}

Ideally the above data it would look like this afterwards:

System                             Type
=======                            ====
Exterior Lights                    Headlights - Forward Adaptive
Exterior Lights                    Headlights - Laser
Exterior Lights                    headlights - LED
Generic                            Launch Control
Mirror                             Blind Spot Assistant
Mirror                             Door Mirror - Integrated LED
Safety                             Tyre Pressure Monitor 
Safety                             ABS

I've tried various combinations of JSON operators but to no avail. Can anyone help?

1 Answer 1

1

You need to first extract the key/value pairs as rows which can be done using jsonb_each(). Then you can use jsonb_array_elements_text() to create a row for each array element:

select x.system, u.type
from the_table t
  cross join jsonb_each(t.data) as x(system, value)
  cross join jsonb_array_elements_text(x.value) as u(type);

Online example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.