PostgreSQL数组(row_to_json()):如何阻止array()函数添加“引用字符串和转义\现有”引号

时间:2015-05-10 05:48:29

标签: arrays json postgresql

尝试将格式正确的JSON对象作为单个字段结果返回。

row_to_json()工作得非常好但返回多行。

SELECT row_to_json(ages) FROM (SELECT DISTINCT RIGHT('000' || TRIM(age),3) AS v FROM uspopulation GROUP BY v ORDER BY v) AS ages

生成的行格式很好,但每行一个:

{"v":"000"}

然后我想将结果集处理成一行/ col结果:

SELECT array(
SELECT row_to_json(ages) FROM (SELECT DISTINCT RIGHT('000' || TRIM(age),3) AS v FROM uspopulation GROUP BY v ORDER BY v) AS ages
);

这实现了期望的结果。但是,它在每个JSON对象周围添加双引号,并转义格式正确的JSON对象中的现有引号。

{"{\"v\":\"000\"}","{\"v\":\"001\"}","{\"v\":\"002\"}"}

那么如何关闭此行为以便得到如下结果:

{{"v":"000"},{"v":"001"},{"v":"002"}}

1 个答案:

答案 0 :(得分:2)

您可以使用json_agg()汇总结果:

SELECT json_agg(ages) FROM
  (SELECT DISTINCT RIGHT('000' || TRIM(age),3) AS v
   FROM uspopulation GROUP BY v ORDER BY v) AS ages;

这将给出正确的输出。请注意,输出不是您所描述的,因为它是一个数组:

[{"v":"000"},{"v":"001"},{"v":"002"}]

我认为这是你想要的,因为它是JSON数组的正确表示法。