我在javascript eval函数中面临以下Json响应对象的问题;期望获取java脚本错误} 由于特殊字符Tamás和Török
{[{"userFirstNm":"Naresh","userAsscId":"70336","userLastNm":"Yashwantrao","userLanId":"a70336"},{"userFirstNm":"Tamás","userAsscId":"37732","userLastNm":"Török","userLanId":"a37732"}]}
是否有任何解决方案可以解决此问题。
alt text http://www.freeimagehosting.net/uploads/a1b09b95d1.png alt text http://www.freeimagehosting.net/uploads/d819fb2191.png
答案 0 :(得分:3)
我知道问题是什么。您需要将对象表达式包装在括号中,以使eval
正常工作。
alert(eval("({\"userFirstNm\":\"Tamás\",\"userAsscId\":\"37732\",\"userLastNm\":\"Török\",\"userLanId\":\"a37732\"})"));
答案 1 :(得分:0)
这本身不是一个JavaScript语句,所以你将无法评估它。
这个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";
产生
Error: SyntaxError: invalid label at line 1: {"userFirstNm":"Tam��s","userAsscId":"37732","userLastNm":"T��r��k","userLanId":"a37732"}
答案 2 :(得分:0)
将字符串放入变量中,然后将其放入var
中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