Reputation:
I have a default setup where I'm defining a bunch of variables like
let a="a", b="b", c="c", d="d", ...
and I got a multidimensional array (as string)
that is using these variables as values like ...
let matrixString = // (typeof matrixString === "string")
`[
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]`
... and I'd like to parse this string using "JSON.parse()"
to get a real array from the string but it looks like there is a issue parsing a string with variables inside because I get the error-message
JSON Parse error: Unexpected identifier "a"
Please have a look at my example:
/* ** default setup ** */
let a="a", b="b", c="c", d="d";
let matrix = [
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]
console.log(matrix)
/* ** here is the issue ** */
let matrixAsString = `[
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]`;
try {
let parsedMatrix = JSON.parse(matrixAsString)
console.log(parsedMatrix)
} catch(error) {
// error = 'JSON Parse error: Unexpected identifier "a"'
console.log(`Error: ${error}`)
}
How to fix this without using a workaround like mapping the string and adding ""
between or using "eval()"
. Is there a method?
Upvotes: 0
Views: 140
Reputation: 56793
You cannot use JSON.parse()
if you don't have JSON
to parse in the first place. If you need a more loose definition of JSON to work for you, consider something like https://www.npmjs.com/package/really-relaxed-json.
In this case, though, what you are looking for might be template literals:
/* ** default setup ** */
let a="1", b="2", c="3", d="4";
let matrix = [
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]
console.log(matrix)
let matrixAsTemplateLiteral = `[
[${a}, ${b}, ${c}, ${d}, ${a}],
[${b}, ${b}, ${c}, ${d}, ${a}],
[${c}, ${c}, ${a}, ${a}, ${d}]
]`;
console.log(matrixAsTemplateLiteral);
Upvotes: 1