开发者

unable to parse json string using java script eval function

I am facing issue with the following Json reponse object in the javascript eval function;Getting java script error expected } because of开发者_如何学运维 special characters Tamás and Török

{
  [{
    "userFirstNm": "Naresh",
    "userAsscId": "70336",
    "userLastNm": "Yashwantrao",
    "userLanId": "a70336"
  }, {
    "userFirstNm": "Tamás",
    "userAsscId": "37732",
    "userLastNm": "Török",
    "userLanId": "a37732"
  }]
}

Is there is any solution to resolve this problem.

unable to parse json string using java script eval function

unable to parse json string using java script eval function


Ah I know what the problem is. You need to wrap the object expression in parentheses for eval to work correctly.

alert(eval("({\"userFirstNm\":\"Tamás\",\"userAsscId\":\"37732\",\"userLastNm\":\"Török\",\"userLanId\":\"a37732\"})"));


That isn't a JavaScript statement by itself, so you won't be able to eval it.

This Perl program runs the JavaScript in SpiderMonkey:

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";

This doesn't print any error messages.

The following:

my $js = JavaScript::SpiderMonkey->new();
$js->init();  # Initialize Runtime/Context
my $rc = $js->eval($stuff);
print "$@\n";

produces

Error: SyntaxError: invalid label at line 1: {"userFirstNm":"Tam��s","userAsscId":"37732","userLastNm":"T��r��k","userLanId":"a37732"}


Put the string into a variable, and then put it into a 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

And a safer alternative is the json_parse function: 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜