JSON的一部分——“;意外标记“;使用构造的JSON字符串

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

本文关键字:JSON 字符串 意外 一部分      更新时间:2023-09-26

这抛出:"未捕获的语法错误:意外的令牌n(…)"。。。

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

没有关于为什么或如何安全解析的线索。

您应该先尝试一个linter。

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

您的text应该是:

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

您有错误的JSON,您应该将键包装成双引号,就像这个

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