SoFunction
Updated on 2025-04-10

Eval JSON object problem with JavaScript

The usual way is to var jsonData = eval(). This seems to be everything correct, but when you run the code, you will find an "invalid labe" error. Why? I'm not sure, but I found a solution to this problem.

I was also very troubled when I first encountered this problem because it seemed that all the encodings were correct. In order to test where the problem occurred, I gradually narrowed the code and finally got the following short code:
Copy the codeThe code is as follows:

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

The above code execution is exactly the invalid labe error mentioned at the beginning. Does the eval function have restrictions on certain expressions or objects? So I tested the array object again, and the code is as follows, and the following code runs normally:
Copy the codeThe 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 is also normal:
Copy the codeThe code is as follows:

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

In the end, I still didn't solve the problem by myself, so I searched the answers online based on the relevant error information. Unexpectedly, I found the root of the problem at once. The solution is "when eval, you must first enclose the JSON string value in '()' brackets." The information I found online did not explain the reason, and of course I still didn't understand the real reason. Parentheses serve as forced first execution or first calculation. The returned JSON is a complete object and there are no expressions in the middle. Why do you need to add brackets? Objects with more complex points like arrays can also be eval normally. There is no way, just remember this usage first. The correct usage is as follows (note the brackets at both ends of eval):
Copy the codeThe code is as follows:

var jsonStr2 = '{"Name":"Tom","Sex":"Man"}';
var jsonObj2 = eval('(' + jsonStr2 + ')');
alert();