Using postgres version 14.x, how do I convert the contents of a column (TEXT type) containing a json array to a csv?
For example
mytable
mycolumn
["10.0.0.1/32", "10.0.0.2/32", "10.0.0.3/32"]
to
10.0.0.1/32,10.0.0.3/32,10.0.0.3/32
Thanks!
Using postgres version 14.x, how do I convert the contents of a column (TEXT type) containing a json array to a csv?
For example
mytable
mycolumn
["10.0.0.1/32", "10.0.0.2/32", "10.0.0.3/32"]
to
10.0.0.1/32,10.0.0.3/32,10.0.0.3/32
Thanks!
2
Answers
you can use
jsonb_array_elements_text
to Expands a JSON array to a set of text values thenstring_agg
to concatenate those values :Simple data :
Result :
Demo here
You can use
REGEXP_REPLACE
to carry out this task.The matching pattern (
[[]"]
) should be a collection of characters to be replaced, namely the open bracket, the closed bracket and the double quote, to be escaped () and enclosed in brackets.
In order to make sure the operation replaces all occurrences of brackets and double quotes, you need to specify
'g'
flag as fourth argument of the functionOutput:
Check the demo here.