Unable to parse json string using java script eval function

I am encountering a problem with the following Json response object in javascript eval function: JavaScript script error expected} due to 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 any solution to solve this problem.

alt text alt text

+4
source share
3 answers

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

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

This is not JavaScript itself, so you won’t be able to evaluate it.

This Perl program launches 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"; 

It does not print error messages.

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 "}
0
source

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

Source: https://habr.com/ru/post/1313466/


All Articles