uuhan
uuhan

Reputation: 153

How to use the key of jsonb in postgresql as a row value?

I have a table like this:

id (serial) | data (jsonb)
1           | {"a": 1, "b": 2}
2           | {"a": 3, "b": 1}

how to convert it to this table:

id | dataKey | dataValue
1  | a       | 1             # {"a": 1} 
1  | b       | 2             # {"b": 2}
2  | a       | 3             # {"a": 3}
2  | b       | 1             # {"b": 1}

ps. character after # is comment

Upvotes: 0

Views: 32

Answers (1)

klin
klin

Reputation: 121474

Use jsonb_each().

with my_table(id, data) as (
values
(1, '{"a": 1, "b": 2}'::jsonb),
(2, '{"a": 3, "b": 1}')
)

select id, key, value
from my_table,
jsonb_each(data)

 id | key | value 
----+-----+-------
  1 | a   | 1
  1 | b   | 2
  2 | a   | 3
  2 | b   | 1
(4 rows)

Upvotes: 1

Related Questions