Home > Web Front-end > JS Tutorial > JavaScript eval JSON object problem_javascript skills

JavaScript eval JSON object problem_javascript skills

WBOY
Release: 2016-05-16 18:41:36
Original
1077 people have browsed it

The usual approach is var jsonData = eval(xmlHttp.responseText). This may seem like everything is correct, but when you run the code, you'll find an "invalid label" error. Why? I don't know either, but I found a way to solve this problem.

It was also a headache when I first encountered this problem, because it seemed that all the coding was correct. In order to test where the problem occurred, I gradually narrowed down the code scope, and finally got the following short code:

Copy code The code is as follows:

var jsonStr1 = '{"Name":"Tom","Sex ":"Man"}';
var jsonObj1 = eval(jsonStr1);
alert(jsonObj1.Name);

The execution of the above code is exactly what the invalid labe said at the beginning mistake. Does the eval function have restrictions on certain expressions or objects? So I tested the array object again, the code is as follows, and the result is that the following code runs normally:
Copy the code The code is as follows:

var arrStr = '["Tom","Man"]';
var arrObj = eval(arrStr);
alert(arrObj[0]);

Could it be that the JavaScript parser on my machine has a problem with JSON parsing, so I tested the following code again, but the result was still normal:
Copy code The code is as follows:

var jsonObj = {"Name":"Tom","Sex":"Man"};
alert(jsonObj.Name);

In the end, I still didn’t solve the problem by myself, so I searched the Internet for answers based on the relevant error messages. Unexpectedly, I found the root of the problem all of a sudden. The solution was “When eval, you must first JSON string values ​​are enclosed in '()' brackets first." The information I found online didn't explain the reason, and of course I still didn't understand the real reason. Parentheses are used to force execution or calculation first. The returned JSON is a complete object with no expressions in the middle. Why do we need to add parentheses! More complex objects like arrays can also be eval normally. There is no other way, just remember this usage first. The correct usage is as follows (pay attention to the brackets at both ends of eval):
Copy the code The code is as follows:

var jsonStr2 = '{"Name":"Tom","Sex":"Man"}';
var jsonObj2 = eval('(' jsonStr2 ')');
alert(jsonObj2.Name);
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template