1

I have the following query:

`SELECT * FROM reports
        WHERE id = ${req.params.id}`

the column type has the following value: "item1,item2,item3".

I want to return it as a JSON array: ["item1","item2","item3"]

I tried this:

`SELECT *, string_to_array(type, ',') AS type FROM reports
        WHERE id = ${req.params.id}`

but I still get it as a plain comma separated string.

Is it possible to do this or I have to convert it manually on the server and not on the query itself?

1 Answer 1

2

Pass the array as argument to to_jsonb():

SELECT to_jsonb(string_to_array(type, ',')) AS type
FROM reports

JSON support was introduced in Postgres 9.3 (json) and 9.4 (jsonb). In the older versions you can try to build a string representing a json array, e.g.:

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

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

           type            
---------------------------
 ["item1","item2","item3"]
(1 row) 
2
  • What is the equiviliant for older Postgres versions such as 8.4?
    – TheUnreal
    Commented Mar 23, 2019 at 11:31
  • Works in 2022 as well!
    – silentsudo
    Commented Jul 21, 2022 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.