Extract key, value from json objects in Postgres
This will solve it as well:
select you_table.id , js.key, js.value
from you_table, json_each(you_table.data) as js
SELECT q.id, d.key, d.value
FROM q
JOIN json_each_text(q.data) d ON true
ORDER BY 1, 2;
The function json_each_text()
is a set returning function so you should use it as a row source. The output of the function is here joined laterally to the table q
, meaning that for each row in the table, each (key, value)
pair from the data
column is joined only to that row so the relationship between the original row and the rows formed from the json
object is maintained.
The table q
can also be a very complicated sub-query (or a VALUES
clause, like in your question). In the function, the appropriate column is used from the result of evaluating that sub-query, so you use only a reference to the alias of the sub-query and the (alias of the) column in the sub-query.