平时经常用到JSON.parse将JSON字符串转换为对象格式,
但有时会遇到不规范的字符串,比如:
'{test: 1}' ( test 没有包围双引号)
'{'test': 1}' (使用了单引号而不是双引号)
如果将上面的字符串传入JSON.parse,会抛出异常。
那么我们就可以使用Eval来进行转换,代码如下:
function handleParse(str) {
return eval("("+str+")");
}
let str = '{"a": 1}';
let b = handleParse(str);
console.log(b); //{a:1}