Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jsonb/array reformatting query

If I have a table which contains the following:

id: 1,
names: ["Dave", "Pete", "Eric"],
ages: [30, 40, 50]

(types are id: int, names: char varying[], ages: int[])

how can I query that to return this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id: 1,
people: [{"name": "Dave", "Age": 30}, {"name": "Pete", "Age": 40}, {"name": "Eric", "Age": 50}]

(types: id: int, people: jsonb (or jsonb[]))

Thanks

>Solution :

You need to use jsonb_build_object to firstly create json objects with name and id data for each record and then combine all objects and form json array using jsonb_agg then group the result based on id to get desired result

Some thing like this :

 SELECT
  id,
  jsonb_agg(
    jsonb_build_object(
      'name', names[i],
      'Age', ages[i]
    )
  ) AS people
 FROM my_table_name, generate_series(1, array_length(names, 1)) AS s(i) GROUP BY id;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading