问题
I have a string that I want to convert into array
"[(6, 11), (12, 17), (18, 20)]"
.split()
wouldn't work (or at least I don't know how to separate the words) and JSON.parse always craps out with Uncaught SyntaxError: Unexpected token
I'm converting like this: JSON.parse(THAT_GIVEN_LIST)
Am I doing something wrong? How do I make this string into a nice list of [(6, 11), (12, 17), (18, 20)]
回答1:
The parentheses that you are using are not syntactically correct for JSON. You pose that they mean to define a tuple. However, tuples are not JSON primitives. If you want to have nested structures like this, your best bet will be to use nested arrays:
const a = "[[6, 11], [12, 17], [18, 20]]";
const aa = JSON.parse(a);
console.log(aa);
aa.forEach(i => console.log(`first: ${i[0]}, second: ${i[1]}`));
回答2:
Having your input format as python list, you can do it in next way:
'use strict';
const tuple = "[(6, 11), (12, 17), (18, 20)]";
const tupleToArray = JSON.parse(tuple
.replace(/\(/g, '[')
.replace(/\)/g, ']')
);
console.log(tupleToArray);
回答3:
Using JSON.parse()
to get the 2-D array. Replaced occurences of "("
with "["
and ")"
with "]"
.
var arr = JSON.parse("[(6, 11), (12, 17), (18, 20)]".split("(").join("[").split(")").join("]"));
console.log(arr);
回答4:
You could do something like I did below. Basically I removed all the white-space from the original string then used regex and split
the string into an array. Finally I used another regex and spread operator to map
the formatted strings to a new array:
var s = "[(6, 11), (12, 17), (18, 20)]";
function makeTuple(str) {
return str
.replace(/\s/g, "")
.split("),(")
.map(el => [...el.replace(/[\[()\]]/g, '').split(',')]);
}
console.log(makeTuple(s));
来源:https://stackoverflow.com/questions/52046119/javascript-converting-string-to-array-of-tuples