eval(); //This method is not recommended
JSON.parse(); //Recommended method
1. The difference between the two methods
We first initialize an object in json format:
var jsonDate = '{ "name":"周星驰","age":23 }' var jsonObj = eval( '(' + jsonDate + ')' ); // eval();方法 var jsonObj = JSON.parse( jsonDate ); // JSON.parse(); 方法
Then call in the console:
console.log( jsonObj.name ); // Both methods can be entered correctly Stephen Chow
Then the question is, what is the difference between the two methods? (Let’s slightly change the code below, the blue font is the modified part)
var jsonDate = '{ "name":alert("hello"),"age":23 }' var jsonObj = eval( '(' + jsonDate + ')' ); // eval();方法 console.log( jsonObj.age ); //会先执行“alert”输出“hello” 然后才输出 23
Replace the "JSON.parse();" method:
var jsonDate = '{ "name":alert("hello"),"age":23 }' var jsonObj = JSON.parse( jsonDate ); // JSON.parse(); 方法 cosole.log( jsonobj.age ) // 报错 这个错误告诉我们这个字符串是不合法的
Summary: The "eval();" method will not determine whether the string is legal when parsing, and the js method in the json object will also be executed, which is very dangerous; and "JSON.parse(); "Needless to say the advantages of this method, this method is recommended. (Friends who don’t understand can test it on the console themselves)
2. Expansion issues
You can see that in the above test, the quotation marks outside the curly braces have been marked in red. This pair of quotation marks is very critical but is often ignored, because "eval();" and "JSON .parser();" The parameters of these two methods only accept strings, which means they can only parse strings!!
Then I have a thought. If we don’t add quotation marks when initializing, then it itself is an object, and js can directly obtain the properties and methods of the object itself; why do we need to add quotation marks to turn it into characters? Then use "eval();" or "JSON.parse();" to parse the string. Isn't this neither environmentally friendly nor efficient?
The reason is very simple: the front-end can only provide string data format to the back-end. What the back-end returns to the front-end depends on the data format returned. If it is a string, it must be parsed before use.
(This is a small problem that everyone generally ignores and doesn’t pay much attention to. The reason why I’m curious is because I don’t know enough about the backend. I post this question in the hope that it will be helpful to friends who are not familiar with the backend and know how it works. It will naturally deepen your memory after the incident, so you won’t miss it during the development process)
The above is the entire content of this article, I hope you all like it.