Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL table to json

I have a table

 key | value
-----+-------
 a   | "foo"
 b   | "bar"

How can I get the result

{"a": "foo", "b": "bar"}

It doesn't work with

select array_to_json(array_agg(t)) from table t; -- I get  [{"key": "a", "value": "foo"}, {"key": "b", "value": "bar"}]

Can you help me?

like image 390
Alexandre Avatar asked Apr 24 '26 05:04

Alexandre


2 Answers

PostgreSQL ≥ 9.4 :

SELECT json_object(array_agg(key), array_agg(value))
FROM  t;     

┌────────────────────────────┐
│        json_object         │
├────────────────────────────┤
│ {"a" : "foo", "b" : "bar"} │
└────────────────────────────┘
(1 row)
like image 57
Marth Avatar answered Apr 26 '26 00:04

Marth


If you are using PostgreSQL 9.4 you can use the following code to take key from one column and value from another and create a single JSON object:

 select json_object(array_agg(key), array_agg(value)) from table;

For earlier versions I don't know of a simple method at this time.

like image 21
Sami Kuhmonen Avatar answered Apr 26 '26 01:04

Sami Kuhmonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!