Flatten a JSONB file – What function/query

All we need is an easy explanation of the problem, so here it is.

In a bit of a pickle at work – I have a Jsonb which I need to flatten a file that has similar structure:

{
   "Manufacturers":[
      {
         "manufacturer":"Tesla",
         "address":"Deer Creek Road Palo Alto",
         "contact":"[email protected]"
      },
      {
         "manufacturer":"BMW",
         "address":"Petuelring 130, 80809 München",
         "contact":"[email protected]"
      }
   ]

I want this in a table format where manufacturing are column names! Something like this – Postgres JSONB – Flatten nested objects and groupings! Can’t seem to understand how to get there. He has mentioned using jsonb_to_recordset but not sure how to get everything in a typical csv format.

Example of how I want to see the data –

Flatten a JSONB file - What function/query

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can indeed use jsonb_to_recordset, but you also need to use -> to pull out the manufacturer property.

Your expected result is unclear, but it looks like you could do this:

SELECT j.*
FROM YourTable t
CROSS JOIN jsonb_to_recordset(t.jsonColumn->'manufacturer')
    AS j(manufacturer varchar(100), address varchar(100), contact varchar(100));

db<>fiddle

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply