Say I have a simple table in postgres as the following:
+--------+--------+----------+ | Car | Pet | Name | +--------+--------+----------+ | BMW |
With JSON functions row_to_json() and json_each_text() you can do it not specifying number and names of columns:
row_to_json()
json_each_text()
select distinct key as col, value as vals from ( select row_to_json(t) r from a_table t ) t, json_each_text(r) order by 1, 2;
SqlFiddle.