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

Expanding jsob array in PostgreSQL to produce analytics

Imagine that we have the following table using jsonb on PostgreSQL:

create table writer
(
  "firstName" varchar,
  "surName"   varchar,
  books       jsonb
);

And the following data is available:

INSERT INTO public.writer ("firstName", "surName", books) VALUES ('William', 'Shakespeare', '[{"name": "Hamlet"}, {"name": "Romeo and Juliet"}]');
INSERT INTO public.writer ("firstName", "surName", books) VALUES ('Agatha', 'Christie', '[{"name": "Hercule Poirot"}, {"name": "Miss Marple"}]');

Is it possible to expand the JSON array to 2 columns similarly to what PowerBI expand does and get the following result?

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

firstName surName bookName
William Shakespeare Hamlet
William Shakespeare Juliet
Agatha Christie Hercule Poirot
Agatha Christie Miss Marple

instead of

firstName surName books
William Shakespeare [{"name": "Hamlet"}, {"name": "Romeo and Juliet"}]
Agatha Christie [{"name": "Hercule Poirot"}, {"name": "Miss Marple"}]

Sample DB: http://sqlfiddle.com/#!17/87ca94/2

>Solution :

You can use jsonb_array_elements() to get one row per array element:

select w."firstName", w."surName", b.book ->> 'name' as book_name
from writer w
  cross join jsonb_array_elements(books) as b(book)

Online example

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