用正斜杠解析 json 字符串 - javascript
parse json string with forward slashes - javascript
看起来很简单,但我想不通
var str="[{name:\"House\",id:\"1\"},{name:\"House and Land\",id:\"5\"},{name:\"Land\",id:\"6\"},{name:\"Terrace\",id:\"11\"}]";
JSON.parse(str.replace(/\s/g, "").replace(/\//g, ''));
我无法将上面的字符串(来自第 3 方网站)转换为有效的 json,以便我可以在我这边对其进行迭代
错误
VM5304:1 Uncaught SyntaxError: Unexpected token n in JSON at position 2
at JSON.parse (<anonymous>)
JSON 需要引用键。看来您的密钥未加引号。因此,添加另一个 .replace
语句以将引号插入:
.replace(/(\w+):/g, '"":');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
Property names must be double-quoted strings; trailing commas are forbidden.
完整的解决方案:
.replace(/(,|{)\s*(\w+)\s*:/g, '"":');
看起来很简单,但我想不通
var str="[{name:\"House\",id:\"1\"},{name:\"House and Land\",id:\"5\"},{name:\"Land\",id:\"6\"},{name:\"Terrace\",id:\"11\"}]";
JSON.parse(str.replace(/\s/g, "").replace(/\//g, ''));
我无法将上面的字符串(来自第 3 方网站)转换为有效的 json,以便我可以在我这边对其进行迭代
错误
VM5304:1 Uncaught SyntaxError: Unexpected token n in JSON at position 2
at JSON.parse (<anonymous>)
JSON 需要引用键。看来您的密钥未加引号。因此,添加另一个 .replace
语句以将引号插入:
.replace(/(\w+):/g, '"":');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
Property names must be double-quoted strings; trailing commas are forbidden.
完整的解决方案:
.replace(/(,|{)\s*(\w+)\s*:/g, '"":');