How to convert PostgreSQL Array in string eg. "{1,2,3,4}"
to javascript/typescript array: [1,2,3,4]
.
The values in the array must be a number type.
I tried a solution with replace and split but it returns string values.
var test = "{1,2,3,4}";
test = test.replace("{", "");
test = test.replace("}", "");
//test = test.replace(/\{|\}/gm, "") //regex replace
test.split(",") //['1', '2', '3', '4']
How to convert PostgreSQL Array in string eg. "{1,2,3,4}"
to javascript/typescript array: [1,2,3,4]
.
The values in the array must be a number type.
I tried a solution with replace and split but it returns string values.
var test = "{1,2,3,4}";
test = test.replace("{", "");
test = test.replace("}", "");
//test = test.replace(/\{|\}/gm, "") //regex replace
test.split(",") //['1', '2', '3', '4']
Share
Improve this question
asked Jan 3, 2019 at 11:24
ambusshambussh
7901 gold badge8 silver badges18 bronze badges
8
- 2 You should not have to do this. The postgresql driver should do it for you. Which one are you using ? – Denys Séguret Commented Jan 3, 2019 at 11:30
-
u can replace curly brackets with square then use JSON.parse method. like this
JSON.parse(test.replace("{", "[").replace("}", "]"))
– shajji Commented Jan 3, 2019 at 11:35 - @DenysSéguret I do not have access to what the entire backend does. – ambussh Commented Jan 3, 2019 at 11:36
- 2 Fixing the backend would probably be the right solution but I know not all projects are ideally managed... – Denys Séguret Commented Jan 3, 2019 at 11:38
- 1 PostgreSQL supports JSON type I remend you use that, it's more efficient and there's no reason to incorrectly format an array in it – nanobar Commented Jan 3, 2019 at 11:43
3 Answers
Reset to default 4A cleaner solution not involving building a JSON string just to parse it:
test = test.match(/[\w.-]+/g).map(Number)
But when dealing with a database you're usually not supposed to parse the data yourself unless you're writing the driver (but there are already good ones for postgresql).
I find solution with JSON.parse but this also need replace before conversion.
var test = "{1,2,3,4}";
test = test.replace("{", "[");
test = test.replace("}", "]");
JSON.parse(test) //[1, 2, 3, 4]
Test with building a string for array size: 100000~900000: https://stackblitz./edit/typescript-gavnpg
JSON.parse("[" + test.slice(1, test.length-1) + "]")