5

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

1 Answer 1

5

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"}'
Sign up to request clarification or add additional context in comments.

1 Comment

this worked for me, I didnt pay attention to this constructor json_object(keys text[], values text[])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.