0

Need help with json deserialization in postgresql. I would like this query

select data from panel

that returns:

                              Data
1 [{"type": "opened","user": "1"},{"type": "added","user":"2"}]
2 [{"type": "added","user": "3"}]
3 [{"type": "opened","user": "3"},{"type": "opened","user":"2"}]

instead returned a table:

type    user
opened  1
added   2
added   3
opened  3
opened  2

I don't quite understand how to represent the empty space between [ and {. I would appreciate any guidance as I have not found this particular example

1 Answer 1

1

Use jsonb_array_elements to turn the arrays in to rows, then extract the keys:

select a.item ->> 'type' as type, 
       a.item ->> 'user' as "user"
from panel
  cross join jsonb_array_elements(data) as a(item);       

This assumes that data is defined with the data type jsonb (which it should be). If it's not, you have to cast it: data::jsonb

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

4 Comments

I'd prefer lateral instead of cross for clarity
Well it is a cross join lateral
Yes, implicitly, I'd just spell it out. And possibly use a second from item not a join at all, so from panel, lateral jsonb_array_elements(panel.data) as a(item)
Well, I prefer to spell out the cross join explicitly rather than implicitly using the comma in the from clause (I never use a comma in the from clause)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.