【发布时间】:2018-09-23 07:47:34
【问题描述】:
我有一个默认设置,我在其中定义了一堆变量,例如
let a="a", b="b", c="c", d="d", ...
我得到了一个多维数组 (as string),它使用这些变量作为值...
let matrixString = // (typeof matrixString === "string")
`[
[a, b, c, d, a],
[b, b, c, d, a],
[c, c, a, a, d]
]`
...我想解析这个字符串使用"JSON.parse()"从字符串得到一个真正的数组,但它看起来在解析带有变量的字符串时出现问题,因为我收到了错误消息
JSON Parse error: Unexpected identifier "a"
请看我的例子:
/* ** 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}`)
}
如何在不使用诸如映射字符串并在其间添加"" 或使用"eval()" 之类的解决方法的情况下解决此问题。 有方法吗?
【问题讨论】:
-
如果您没有要解析的 JSON,请不要使用
JSON.parse()。 -
除了使用 JSON.parse 之外,您还有其他方法吗?
-
编写自己的解析方法。或者考虑使用relaxedjson.org
-
这是您要找的吗? js-chfrhm.stackblitz.io
-
为什么不把字符串写成某个对象的键、值对的形式,然后在上面使用 JSON.parse 呢?例如,您可以将您现在拥有的字符串包装在
{data: ${2dArrayString}}中。
标签: javascript json parsing math matrix