eval (); This method is not recommended
Json.parse (); Recommended method
The difference between the two methods
Let's start by initializing a JSON-formatted object:
var jsondate = ' {' name ': ' Stephen Chow Chi ', ' age ': 23} '
var jsonobj = eval (' (' + jsondate + ') '); eval (); method
var jsonobj = Json.parse (jsondate); Json.parse (); Method
Then in the console call:
Console.log (Jsonobj.name); Both of these methods can be entered correctly Stephen Chow Chi
So what's the difference between the two ways? (Let's change the code a bit, the blue font is the modified part)
var jsondate = ' {' Name ': Alert ("Hello"), "Age": 23} '
var jsonobj = eval (' (' + jsondate + ') '); eval (); method
Console.log (Jsonobj.age); "Alert" Output "Hello" will be executed before output 23
Change "json.parse ();" Method:
var jsondate = ' {' Name ': Alert ("Hello"), "Age": 23} '
var jsonobj = Json.parse (jsondate); Json.parse (); Method
Cosole.log (Jsonobj.age)//The error tells us that this string is illegal
Summary: "eval ();" The method parsing is not to judge whether the string is legitimate, and the JSON object in the JS method will be executed, which is very dangerous, and "json.parse ();" The advantage of the method is not to say much, recommend this method. (Do not understand the pot friends can test themselves in the console)
II. Expansion issues
var jsondate = ' {' name ': ' Stephen Chow Chi ', ' age ': 23} '
As you can see, the quotation marks that are wrapped around the curly braces in red are always highlighted in the test above, which is critical but often overlooked, because "eval ();" and "Json.parser ();" The arguments for both methods only accept strings, that is, only strings can be parsed!!
Then I do not have a thought, when we initialize the time without quotation marks, then it is the object itself, JS can directly get the properties and methods of the object itself, why also quote it into a string after the "eval ();" or "json.parse ();" Parse, Is it not environmentally friendly and inefficient?
The reason is simple: the front-end provided to the background can only be string data format, back to the foreground in the background to see what data format returned, is the string must be parsed and then used.
(This small problem is generally ignored, not too much attention.) I am curious because the background is not enough to know, throw this issue to hope that the background is not familiar with the friends to help, know how to go back after the natural memory, in the development process will not miss out)
Two ways to parse JSON in Ajax