JSON.parse 与 eval() 对于解析json的问题(
from:https://www.cnblogs.com/zqzjs/p/4693958.html
1.eval()与JSOn.parse的不同
eval()

varc = 1;//全局变量varjsonstr1 = '{"name":"a","company":"b","value":++c}';varjson1 = eval('(' + jsonstr1 + ')');
console.log(json1.value);


c是全局变量为1,但是经过eval的解析,全局变量变成了2!(这样的写法是危险的)
JSON.parse

varc = 1;//全局变量varjsonstr1 = '{"name":"a","company":"b","value":++c}';varjson2 =JSON.parse(jsonstr1);
console.log(json2.value);

IE下报错:

谷歌下报错:

而JSON.parse则会报错。
2.在++c中加上双引号则就可以,因为它变成字符串了。

varc = 1;//全局变量varjsonstr1 = '{"name":"a","company":"b","value":“++c”}';varjson2 =JSON.parse(jsonstr1);
console.log(json2.value);

结果:

3.我想很多人在纠结双引号的问题,这里我们就来集中测试下。
a:JSON.parse

varc = 1;//全局变量vardate =newDate();
console.log(date.toLocaleDateString());//var jsonstr1 = '{"name":"a","company":"b","value":"++c"}';//键,值都有双引号varjsonstr2 = '{"name":"a","company":"b","value":++c}';//仅++c上午双引号//var jsonstr3 = '{name:"a",company:"b",value:"++c"}';//仅有值上有双引号//var jsonstr4 = '{name:a,company:b,value:++c}';//全无双引号//var json1 = JSON.parse(jsonstr1);varjson2 =JSON.parse(jsonstr2);//var json3 = JSON.parse(jsonstr3);//var json4 = JSON.parse(jsonstr4);//console.log(json1 );console.log(json2 );//console.log(json3);//console.log(json4);

结果依次为:




可见JSON.parse中只有第一种标准形式才会解析正确
b:eval()

varc = 1;//全局变量vardate =newDate();
console.log(date.toLocaleDateString());varjsonstr1 = '{"name":"a","company":"b","value":"++c"}';//键,值都有双引号//var jsonstr2 = '{"name":"a","company":"b","value":++c}';//仅++c上午双引号//var jsonstr3 = '{name:"a",company:"b",value:"++c"}';//仅有值上有双引号//var jsonstr4 = '{name:a,company:b,value:++c}';//全无双引号varjson1 = eval('('+jsonstr1+')');//var json2 = eval('('+jsonstr2+')');//var json3 = eval('('+jsonstr3+')');//var json4 = eval('('+jsonstr4+')');console.log(json1+" "+json1.value );//console.log(json2+" "+json2.value );//console.log(json3 + " " + json3.value);//console.log(json4+" "+json3.value);

结果依次为:




而eval中除了最后一种,其他都解析正确。
4.这时候还有一个问题:那就是为什么eval()解析的时候要加上括号?
我们先看看不加括号会怎么样:

varc = 1;//全局变量vardate =newDate();
console.log(date.toLocaleDateString());varjsonstr1 = '{"name":"a","company":"b","value":"++c"}';//键,值都有双引号varjson1 =eval(jsonstr1);
console.log(json1+" "+json1.value );

结果:

这里不加就出错了。
那是因为eval()相当于一个执行环境,当你不加括号的时候,jsonstr1会被认为是一条复合语句。运行的时候就会逐个字符的解析。
但是加上括号的时候,jsonstr1就当做一个表达式去运算。从括号开始就被当做了对象进行识别。
5.然后你又会想到,那这个括号为什么要加“()”,不能加“{}”么?
答案是:当然能加“{}”,只不过就会报错而已~。— —!
这时候你要明吧json的格式是什么!
{"name":"a","company":"b"} 这就是标准形式。