Skip to content
Advertisement

SQL: extract keys and values of a jsonb field as rows of two separate columns

In my postgresql DB I have the following query

returning

where json_field is of type JSONB.

I am looking for a way to query all the keys and all the values from this json field, so that the output would be

Is there a way to do it ?


generalizing the question after it got the solution answer

When I wrote the question I did not paid attention, so I implicitly asked not only to extract keys and values of a jsonb field as rows of two separate columns, but also – assuming that all the values associated to the key were 1 element-long arrays – to select only the value of the first element of the list in the value associated to each key.
The solution given by stefanov.fm does so.

Now, to generalize the answer, in case the first query result were

then the desired second query is

thanks to @stefanov.fm

Advertisement

Answer

Use jsonb_each function.

Here is an illustration with your data as a literal.

key value
beta 10002
alpha 10001
gamma 10003
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement