2013-10-15 41 views
2

鑑於此查詢: -的Postgres 9.3 JSON輸出多維對象

SELECT id as id, 
     attributes->>'name' as file_name, 
     status 
from workflow.events 
where schema='customer' 
    and type='FILE_UPLOAD' 

id,file_name, status 
1,name,status 
2,name2,status2 

我要輸出這樣的結構: -

{ 
"1" :{"id" :"1", "file_name" : "name", "status" : "status1"}, 
"2" :{"id" :"2", "file_name" : "name2","status" : "status2"} 
} 

我可以用字符串函數在此刻做,但這個似乎凌亂和低效。 CAn它使用本地postgresql json函數完成?

+0

可能重複http://stackoverflow.com/ questions/11198625/json-output-in-postgresql) – 2013-10-15 11:11:14

+2

有幾個有用的json函數,即row_to_json(),它應該派上用場:http://www.postgresql.org/docs/current/static/functions -json.html –

回答

4

如果你想獲得兩個記錄,JSON,使用row_to_json()功能:

with cte as (
    select 
     id as id, 
     attributes->>'name' as file_name, 
     status 
    from workflow.events 
    where schema='customer' and type='FILE_UPLOAD' 
) 
select row_to_json(c) from cte as c 

輸出:

{"id":1,"file_name":"name","status":"status"} 
{"id":2,"file_name":"name2","status":"status2"} 

如果你想獲得JSON數組:

with cte as (
    select 
     id as id, 
     attributes->>'name' as file_name, 
     status 
    from workflow.events 
    where schema='customer' and type='FILE_UPLOAD' 
) 
select json_agg(c) from cte as c 

輸出:

[{"id":1,"file_name":"name","status":"status"}, 
{"id":2,"file_name":"name2","status":"status2"}] 

但你需要的輸出,我只能建議字符串轉換:

with cte as (
    select 
     id::text as id, 
     file_name, 
     status 
    from workflow.events 
    where schema='customer' and type='FILE_UPLOAD' 
) 
select ('{' || string_agg('"' || id || '":' || row_to_json(c), ',') || '}')::json from cte as c 

sql fiddle demo

[在PostgreSQL JSON輸出(的
+0

最後一步是串聯,在'row_to_json()'完成大部分工作後應該足夠好。我會刪除你的答案,因爲你沒有刪除你的答案,你的答案是好的。 –

+0

謝謝@ErwinBrandstetter,我看到PostgreSQL有json_each從結構像這樣的輸出獲取數據,但似乎沒有這樣做的功能,因爲OP想要: –

+0

關於這些功能的例子很少在postgres 9.3中使用JSON,這個答案是有啓發性的!謝謝羅馬 – colthreepv