Postgresql-在select查询中返回json数组,而不是逗号分隔的值

Postgresql-在select查询中返回json数组,而不是逗号分隔的值,postgresql,Postgresql,我有以下疑问: `SELECT * FROM reports WHERE id = ${req.params.id}` 列type具有以下值:“item1、item2、item3” 我想将其作为JSON数组返回:[“item1”、“item2”、“item3”] 我试过这个: `SELECT *, string_to_array(type, ',') AS type FROM reports WHERE id = ${req.params.id}` 但我仍然把

我有以下疑问:

`SELECT * FROM reports
        WHERE id = ${req.params.id}`
type
具有以下值:
“item1、item2、item3”

我想将其作为JSON数组返回:
[“item1”、“item2”、“item3”]

我试过这个:

`SELECT *, string_to_array(type, ',') AS type FROM reports
        WHERE id = ${req.params.id}`
但我仍然把它理解为一个简单的逗号分隔字符串


是否可以这样做,或者我必须在服务器上而不是在查询本身上手动转换它?

将数组作为参数传递给:

JSON支持是在postgres9.3(JSON)和9.4(jsonb)中引入的。在旧版本中,您可以尝试构建表示json数组的字符串,例如:

with report(type) as (
    values ('item1,item2,item3')
)

select '[' || regexp_replace(type, '([^,]+)', '"\1"', 'g') || ']' as type
from report

           type            
---------------------------
 ["item1","item2","item3"]
(1 row) 

对于较旧的Postgres版本,如8.4,其等效性是什么?
with report(type) as (
    values ('item1,item2,item3')
)

select '[' || regexp_replace(type, '([^,]+)', '"\1"', 'g') || ']' as type
from report

           type            
---------------------------
 ["item1","item2","item3"]
(1 row)