abugnais
abugnais

Reputation: 188

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

I have a key-value postgresql table with this form

pk | fk | key | value
---|----|-----|------
1  | 11 | k1  | v1
2  | 11 | k2  | v2
3  | 22 | k3  | v3
4  | 33 | k1  | v1
5  | 33 | kk  | vk
6  | 33 | kn  | vn

that i need to convert to json objects grouped by fk:

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

I've already found a way to do this using and intermediate hstore conversion:

SELECT fk, hstore_to_json(hstore(array_agg(key), array_agg(value))) as kv
FROM tbl
GROUP BY fk, pk;

the issue is, hstore extension is not available for me on production, and I can't install it, is there another way to get the same form of output?

PS: postgresql version is 9.4.8

Upvotes: 5

Views: 1068

Answers (1)

Patrick
Patrick

Reputation: 32199

It's actually very similar to the hstore version:

SELECT fk, json_object(array_agg(key), array_agg(value)) AS kv
FROM tbl
GROUP BY fk
ORDER BY fk;

Yields:

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

Upvotes: 5

Related Questions