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
To convert this PostgreSQL array into JSON, we can use the array_to_json function.
PostgreSQL provides two native operators -> and ->> to help you query JSON data. The operator -> returns JSON object field as JSON. The operator ->> returns JSON object field as text.
A PostgreSQL multidimensional array becomes a JSON array of arrays. Line feeds will be added between dimension 1 elements if pretty_bool is true. Syntax: array_to_json(anyarray [, pretty_bool]) Return Type.
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"}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With