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.
1 Answer1
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
user330315
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
