2015-04-07 25 views
0

我有一個表PostgreSQL表以JSON

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

我怎樣才能得到結果

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

它不

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

你能幫助我工作嗎?

+0

http://dba.stackexchange.com/questions/90482/export-postgres-table-as-json – svenhornberg

+1

@fuubah不是同一個問題。在這個問題中,表格數據將與列名一起輸出。這裏列名不重要,但是表中的數據。 –

+0

可能相關:http://stackoverflow.com/questions/20069143/postgres-inverse-of-json-each – dhke

回答

1

的PostgreSQL≥9.4:

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

┌────────────────────────────┐ 
│  json_object   │ 
├────────────────────────────┤ 
│ {"a" : "foo", "b" : "bar"} │ 
└────────────────────────────┘ 
(1 row) 
1

如果您在使用PostgreSQL 9.4,你可以使用下面的代碼把鑰匙從一列值,從另一個並創建一個單一的JSON對象:

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

對於早期版本我不知道的簡單的方法在這個時候。