Postgresql: how to convert a key value table into json without using an intermediate hstore Postgresql: how to convert a key value table into json without using an intermediate hstore json json

Postgresql: how to convert a key value table into json without using an intermediate hstore


It's actually very similar to the hstore version:

SELECT fk, json_object(array_agg(key), array_agg(value)) AS kvFROM tblGROUP BY fkORDER BY fk;

Yields:

fk |                 kv---+------------------------------------------11 | '{"k1" : "v1", "k2" : "v2"}'22 | '{"k3" : "v3"}'33 | '{"k1" : "v1", "kk" : "vk", "kn" : "vn"}'