简体   繁体   English

将 js 对象(以字符串形式)转换为 JSON

[英]Convert js-object (in a string) to JSON

Having a valid JS Object (ES6 formatted with trailing comma) in a string in for example a browser or node , how to get a valid JSON-object out of this?在例如浏览器节点的字符串中具有有效的 JS 对象(ES6 格式为尾逗号),如何从中获取有效的 JSON 对象? https://www.convertsimple.com/convert-javascript-to-json/ does it for example.例如, https: //www.convertsimple.com/convert-javascript-to-json/ 就是这样做的。

"Of course" I know about JSON.parse and JSON.stringify but not sure it can do the trick in this case. “当然”我知道 JSON.parse 和 JSON.stringify,但不确定在这种情况下它是否可以解决问题。 :) (Or at least, I don't see how). :)(或者至少,我不明白如何)。 I also would like to avoid eval .我也想避免eval

Example:例子:

const jsObjectInString = `{
  key: "value",
  test: 1,
  result: [
    {
      subKeyOne: "test"
    },
    {
      subKeyTwo: "test value with space",
      test: 2
    }
  ],
}`;

Expected result:预期结果:

{
  "key": "value",
  "test": 1,
  "result": [
    {
      "subKeyOne": "test"
    },
    {
      "subKeyTwo": "test value with space",
      "test": 2
    }
  ]
}

You'll need a JavaScript parser.您将需要一个 JavaScript 解析器。 You can use the one built into the JavaScript environment where your code is running, but you have to be sure that the string doesn't contain anything malicious, etc., since it won't just parse the code but will also execute it.您可以使用内置于运行代码的 JavaScript 环境中的那个,但您必须确保该字符串不包含任何恶意等内容,因为它不仅会解析代码,还会执行它。 So it's essential that you don't accept the string from User A and then "parse" it (run it) on User B's machine (unless User B explicitly allows it, like here on SO).因此,重要的是您不要接受来自用户 A 的字符串,然后在用户 B 的机器上“解析”它(运行它)(除非用户 B 明确允许它,就像在这里一样)。

But if you don't trust the source, there are parsers for JavaScript written in JavaScript, such as Esprima , which will give you an AST of the parsed code ( like this ), which you can then use to build the resulting JSON.但是,如果您不信任源代码,则可以使用 JavaScript 编写的 JavaScript 解析器,例如Esprima ,它会为您提供已解析代码的 AST( 如下所示),然后您可以使用它来构建生成的 JSON。

Here's the approach if you can trust the source of the string :如果您可以信任字符串的来源,则可以使用以下方法:

 const jsObjectInString = `{ key: "value", test: 1, result: [ { subKeyOne: "test" }, { subKeyTwo: "test value with space", test: 2 } ], }`; // The `(0, eval)(...)` thing is called "indirect eval" and it's there to // prevent `eval` from getting access to the scope where you call it const json = JSON.stringify( (0, eval)("(" + jsObjectInString + ")"), null, 4 ); console.log(json);

Two things to note there:有两点需要注意:

  1. We don't call eval directly, because eval is magic and gets access to local scope when you call it directly.我们不直接调用eval ,因为eval很神奇,当您直接调用它时,它可以访问本地范围。 If you call it indirectly (as above), it doesn't get access to local scope.如果您间接调用它(如上所述),则它无法访问本地范围。
  2. We wrap the object in () since otherwise the first { looks like the start of a block to the parser.我们将对象包装在() ,否则第一个{看起来就像解析器的块的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM