3

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']
8
  • 2
    You should not have to do this. The postgresql driver should do it for you. Which one are you using ? 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("}", "]")) Commented Jan 3, 2019 at 11:35
  • @DenysSéguret I do not have access to what the entire backend does. 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... Commented Jan 3, 2019 at 11:38
  • 1
    PostgreSQL supports JSON type I recommend you use that, it's more efficient and there's no reason to incorrectly format an array in it Commented Jan 3, 2019 at 11:43

3 Answers 3

4

A 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).

Sign up to request clarification or add additional context in comments.

Comments

1

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.com/edit/typescript-gavnpg

Comments

1
JSON.parse("[" + test.slice(1, test.length-1) + "]")

1 Comment

Please add context to your answer explaining how this is a solution to the problem. Thanks! --From Review

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.