鉴于此查询: -
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"}
}
我现在可以使用字符串函数来执行此操作,但这看起来很混乱且效率低下。可以使用本机postgresql json函数完成吗?
答案 0 :(得分: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 强>