JSON.parse — "unexpected token" 构造 JSON 字符串

JSON.parse — "unexpected token" with constructed JSON string

这抛出:"Uncaught SyntaxError: Unexpected token n(…)" ...

var text = "notation: 'fixed', precision: 2";
JSON.parse("{" + text + "}");

不知道为什么或如何安全解析。

你应该先尝试 a linter

问题是您在 text 中对 key/value 使用了单引号,或者根本没有使用。

您的 text 应该是:

var text = '"notation": "fixed", "precision": "2"';

你错了JSON,你应该把键用双引号括起来,像这样

var text = "notation: 'fixed', precision: 2";
text = text.replace(/\'/g, '"').replace(/(\w+):/g, '"":');
console.log( JSON.parse("{" + text + "}") );