【问题标题】:Parse array-like string containing variable names to array将包含变量名的类数组字符串解析为数组
【发布时间】: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


【解决方案1】:

如果您首先没有 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2017-02-02
    • 1970-01-01
    相关资源
    最近更新 更多