关于 eval 的报错 Uncaught ReferenceError: False is not defined
var obj ={'id': 16, 'name': '管理员', 'delflag': False, 'grade': 1000000.0}
VM3614:1 Uncaught ReferenceError: False is not defined
at <anonymous>:1:47
(anonymous) @ VM3614:1
var obj
undefined
obj ={'id': 16, 'name': '管理员', 'delflag': False, 'grade': 1000000.0}
VM3633:1 Uncaught ReferenceError: False is not defined
at <anonymous>:1:43
(anonymous) @ VM3633:1
obj = "{'id': 16, 'name': '管理员', 'delflag': False, 'grade': 1000000.0}"
"{'id': 16, 'name': '管理员', 'delflag': False, 'grade': 1000000.0}"
alert(obj)
undefined
var oo =eval("("+obj+")")
VM3699:1 Uncaught ReferenceError: False is not defined
at eval (eval at <anonymous> ((index):1), <anonymous>:1:39)
at <anonymous>:1:9
(anonymous) @ VM3699:1
(anonymous) @ VM3698:1
var oo =eval(obj)
VM3724:1 Uncaught SyntaxError: Unexpected token :
at <anonymous>:1:14
(anonymous) @ VM3723:1
obj
"{'id': 16, 'name': '管理员', 'delflag': False, 'grade': 1000000.0}"
typeof obj
"string"
obj ={'id': 16, 'name': '管理员', 'delflag': False, 'grade': 1000000.0}
VM3755:1 Uncaught ReferenceError: False is not defined
at <anonymous>:1:43
(anonymous) @ VM3755:1
obj ={'id': 16, 'name': '管理员', 'grade': 1000000.0}
{id: 16, name: "管理员", grade: 1000000}
alert(obj)
undefined
var test =eval("("+obj+")")
VM3847:1 Uncaught SyntaxError: Unexpected identifier
at <anonymous>:1:23
(anonymous) @ VM3846:1
var test =eval("("+"obj"+")")
undefined
typeof test
"object"
alert(test)
undefined
原因是:字典里存储了一个False的变量,js无法识别,SO 报错,
更重要的是,因为不是正规的json格式,所以会报错,正规的 key 是必须要有双引号的。(即使是单引号也不行。)
错误代码:
var res = "[{id:1,name:'liming'},{id:2,name:'xiaobai'}]";
var objRes = JSON.parse(res);
console.log(objRes)
1
2
3
正确代码:
var res = '[{"id":1,"name":"liming"},{"id":2,"name":"xiaobai"}]';
var objRes = JSON.parse(res);
console.log(objRes)