javascript - 将包含变量名称的类似数组的字符串解析为数组

标签 javascript json parsing math matrix

我有一个默认设置,我定义了一堆变量,例如

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 定义来为您工作,请考虑类似 https://www.npmjs.com/package/really-relaxed-json 的内容。 .

但在这种情况下,您要查找的可能是模板文字:

/* ** 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);

关于javascript - 将包含变量名称的类似数组的字符串解析为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52464105/

相关文章:

javascript - 在将项目发送到服务器之前累积项目 ID 的最佳方法是什么?

python - Python 中的方程解析

php - 使用正则表达式解析 SQL,排除带引号的文字

javascript - 显示 json 文件的前 20 项

ios - 如何从 json 字典自动创建模型类(NSObject)?

json - 通过 application/json curl 请求发送 bool 值

javascript - 从 JSON 生成带有 JS 的 HTML 页面

javascript - 引导 Accordion : Not Auto-Collapsing when another is clicked

javascript - 如何在javascript代码中更改django模板变量值?

javascript - 还有比 jQuery 内置的 XML 解析器更强大的吗?