eval
正确地工作。alert(eval("({\"userFirstNm\":\"Tamás\",\"userAsscId\":\"37732\",\"userLastNm\":\"Török\",\"userLanId\":\"a37732\"})"));
这本身不是一个JavaScript语句,所以你不能对其进行eval操作。
这个Perl程序可以在SpiderMonkey中运行JavaScript代码:
use warnings;
use strict;
use JavaScript::SpiderMonkey;
my $stuff = '{"userFirstNm":"Tamás","userAsscId":"37732","userLastNm":"Török","userLanId":"a37732"}';
my $stuff2 = "var k = new Object ($stuff)";
my $js2 = JavaScript::SpiderMonkey->new();
$js2->init(); # Initialize Runtime/Context
my $rc2 = $js2->eval($stuff2);
print "$@\n";
这不会打印任何错误信息。
以下内容:
my $js = JavaScript::SpiderMonkey->new();
$js->init(); # Initialize Runtime/Context
my $rc = $js->eval($stuff);
print "$@\n";
生成
错误:语法错误:第1行无效标签:{"userFirstNm":"Tam��s","userAsscId":"37732","userLastNm":"T��r��k","userLanId":"a37732"}
var str = '{"userFirstNm":"Tamás","userAsscId":"37732","userLastNm":"Török","userLanId":"a37732"}';
eval("var obj=" + str);
console.debug ? console.debug(obj) : alert(obj); //outputs the object
而更安全的选择是使用json_parse函数:http://www.json.org/json_parse.js;
var obj = json_parse('{"userFirstNm":"Tamás","userAsscId":"37732","userLastNm":"Török","userLanId":"a37732"}');
console.debug ? console.debug(obj) : alert(obj); //outputs the object