Comparative analysis of two methods of Json in Ajax

  • 2020-06-22 23:28:59
  • OfStack

eval (); // This method is not recommended

JSON. parse (); // Recommended methods

1. The difference between the two methods

We first initialize an object in json format:


  var jsonDate = '{ "name":" Stephen chow ","age":23 }'

  var jsonObj = eval( '(' + jsonDate + ')' ); // eval(); methods 

  var jsonObj = JSON.parse( jsonDate ); // JSON.parse();  methods 

Then call in the console:

console. log (jsonObj. name); // Both methods can input Stephen Chow correctly

So the question is what's the difference between the two approaches? (Let's change the code a little bit, and the blue font is the modified part)


  var jsonDate = '{ "name":alert("hello"),"age":23 }'

  var jsonObj = eval( '(' + jsonDate + ')' ); // eval(); methods 

  console.log( jsonObj.age ); // Will execute first" alert "Output" hello "   And then output it  23

In "JSON. parse ();" Methods:


  var jsonDate = '{ "name":alert("hello"),"age":23 }'

  var jsonObj = JSON.parse( jsonDate ); // JSON.parse();  methods 

  cosole.log( jsonobj.age ) //  An error   This error tells us that the string is not valid 

Summary: "eval ();" Method parsing does not determine if the string is valid, and the js method in the json object is executed, which is very dangerous. While "JSON. parse ();" The advantages of the method are not discussed, and it is recommended. (If you don't understand, you can test 1 in the console.)

2. Expand the problem


var jsonDate = '{ "name":" Stephen chow ","age":23 }'

You can see that in the above test 1 is marked in straight red with the quotes around the curly braces, which are critical but often ignored because "eval();" And "JSON. parser ();" The arguments to these two methods only accept strings, which means only strings can be parsed!!

So I don't have to think, if we initialize it without quotation marks, then it is an object itself, js can directly get the properties and methods of the object itself; Why put quotes around it to make it a string and then use "eval();" Or "JSON. parse ();" M: Well, it's not environmentally friendly and it's not efficient.

The reason is very simple: what the front end provides to the background can only be the string data format, and what the back end returns to the front end depends on what data format it returns. If it is a string, it must be parsed and used later.

This little problem is usually ignored and not paid much attention to. The reason why I am curious is also because I don't know enough about the background. I throw this question out in the hope that it will be of some help to my friends who are not familiar with the background. Knowing what happened will naturally deepen my memory and I won't miss it in the development process.

This is the end of this article, I hope you enjoy it.


Related articles: