Postgres中的Array_agg选择性引用

Fra*_*nry 1 arrays postgresql json aggregate-functions

我有一个复杂的数据库,其中的键和值存储在不同的表中。当为应用程序提取值时,对它们进行汇总很有用:

   SELECT array_agg(key_name), array_agg(vals)
                    FROM (
                        SELECT
                            id,
                            key_name,
                            array_agg(value)::VARCHAR(255) AS vals
                        FROM factor_key_values
                        WHERE id=20
                        GROUP BY key_name, id
                    ) f;
Run Code Online (Sandbox Code Playgroud)

在我的情况下,此特定查询给出以下无效的JSON:

-[ RECORD 1 ]-----------------------------------------------------------------------  
array_agg | {"comparison method","field score","field value"} 
array_agg | {"{\"text category\"}","{100,70,50,0,30}","{A,B,C,F,\"No Experience\"}"}
Run Code Online (Sandbox Code Playgroud)

请注意,仅在字符串包含空格的情况下才引用varchars数组。我将其范围缩小到的行为ARRAY_AGG。为了完整起见,下面是一个示例:

BEGIN;
CREATE TABLE test (txt VARCHAR(255));
INSERT INTO test(txt) VALUES ('one'),('two'),('three'), ('four five');
SELECT array_agg(txt) FROM test;
Run Code Online (Sandbox Code Playgroud)

结果将是:

{one,two,three,"four five"}
Run Code Online (Sandbox Code Playgroud)

这就是为什么我的JSON损坏的原因。我可以处理应用程序代码中未加引号或字符串的字符串,但有一些混淆。

有什么解决办法吗?

Clo*_*eto 5

你不能用json_agg吗?

select json_agg(txt) from test;
               json_agg               
--------------------------------------
 ["one", "two", "three", "four five"]
Run Code Online (Sandbox Code Playgroud)