2013-10-15 42 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