I have a string like this: var data = "[[1, 2, 3,], [3, 2, 1]]";
I am using the well known blossom function, which expects (as input) an array of this type: [[1, 2, 3,], [3, 2, 1]], [...], [...]]
As you can see, I am trying to provide this with my: data variable, but this is currently a string, so I need to convert it to the right type. I know that I can convert a string to an array like this:
var input = "1, 2, 3";
var array = input.split(",");
Then the result of the above will be: ["1", "2", "3"]
But I need to be able to give input like this: var data = "[[1, 2, 3,], [3, 2, 1]]";
And expect this output: [[1, 2, 3,], [3, 2, 1]];
Also, notice that the values in the brackets are numbers and not string.
I also tried doing this:
var data = "[1, 2, 3,], [3, 2, 1]";
var res = data.split(",");
This gives the output: ["[1", " 2", " 3", "]", " [3", " 2", " 1]"]
Finally I also found this example: Convert string with commas to array where the solution made use of JSON.parse(...), but I did not make this work either.
2 Answers 2
If your array have trailing commas you can use this code:
var data = "[[1, 2, 3,], [3, 2, 1]]";
var array = JSON.parse(data.replace(/,\s*]/g, ']'));
console.log(array);
and if you have string like this:
var data = "[1, 2, 3,], [3, 2, 1]";
use
var array = JSON.parse('[' + data.replace(/,\s*]/g, ']') + ']');
Example:
var data = "[1, 2, 3,], [3, 2, 1]";
var array = JSON.parse('[' + data.replace(/,\s*]/g, ']') + ']');
console.log(array);
5 Comments
As I said in comment, this isn't JSON, as there are trailing commas.
Modifying a string which isn't in JSON to make it possible to use JSON.parse looks like a silly hack, especially when a proper parsing is easy.
An alternative would be:
var arr = str.split(/[\[\]]+,?\s*/)
.filter(Boolean)
.map(s=>s.split(/\D+/).filter(Boolean).map(Number));
JSON.parse. If it is then just go for it.Functionconstructor as a substitute foreval. It evaluates the code just like any other script, hence the trust caveat, but by usingFunctionit at least gets eval'd as though the function was created in the global scope, and it avoids performance problems.var array = new Function("return " + data)();