Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 906
abugnais Avatar asked Jun 12 '16 09:06

abugnais


People also ask

Which function converts a table row to JSON in PostgreSQL?

To convert this PostgreSQL array into JSON, we can use the array_to_json function.

What is ->> in Postgres?

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.

What is JSON array elements PostgreSQL?

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.


1 Answers

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"}'
like image 175
Patrick Avatar answered Sep 21 '22 07:09

Patrick