1

I have ajsonb structure like this:

{  "id": "id1",  "someObject": {    "key1": [       "abc",       "xyz"    ],    "key2": [       "abc",       "xyz"    ]  }}

I want to translate it into a row-column representation like below:

|  id  |  keys   |    values   || ---- | ------- | ----------- || id1  |  key1   |    abc      || id1  |  key1   |    xyz      || id1  |  key2   |    abc      || id1  |  key2   |    xyz      |

I cannot use thekeys (likekey1 orkey2) in the query because they are different across different objects.

I tried using Postgres' jsonb functions but couldn't find a solution.

How can I do this using a short query?

Thanks in advance.

askedAug 9, 2022 at 9:18
Abhinav's user avatar
0

1 Answer1

2

You can usejsonb_each to iterate over the keys. This can be combined withjsonb_array_elements_text() to get the array elements for each key:

select t.the_column ->> 'id' as id,        o.key,        x.valuefrom the_table t  cross join jsonb_each(t.the_column -> 'someObject') as o(key, element)  cross join jsonb_array_elements_text(o.element) as x(value)
answeredAug 9, 2022 at 9:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.