Js USES eval to parse json in json of js

  • 2020-03-30 01:24:33
  • OfStack

Let's start with the use of eval, which is easy to skip over if you're familiar with it
The eval function takes an argument s, and if s is not a string, returns s directly. Otherwise, execute the s statement. Returns a value if the result of the s statement execution is a value, otherwise returns undefined. It is important to note that the object declaration syntax "{}" does not return a value. It needs to be enclosed in parentheses to return a value. A simple example is as follows:


var s1='"a" + 2'; //expression
var s2='{a:2}'; // statements 
alert(eval(s1)); //->'a2'
alert(eval(s2)); //->undefined
alert(eval('(' + s2 + ')')); //->[object Object] 

As you can see, for an object declaration statement, just execution does not return a value.

In order to return a commonly used object declaration such as' {} ', you must enclose it in parentheses to convert it into an expression in order to return its value. This is one of the fundamental principles of using JSON for Ajax development. As you can see clearly in the example, the second alert statement outputs undefined, and the third, bracketed, outputs the object that the statement represents.
Now the focus of this article is how to execute global code within functions. To illustrate this, let's look at an example:


var s='global'; //Define a global variable
function demo1(){
    eval('var s="local"');
}
demo1();
alert(s); //->global 

It is easy to understand that the demo1 function above is equivalent to: function demo1(){var s='local'; }, where a local variable s is defined.
So it's not surprising that the final output is global, because we can clearly distinguish between local variables and global variables.
On closer inspection, you can see the eval function's characteristic that it is always executed in the context variable space where it is called (also known as package, closure), both in the variable definition and in the function definition, so the following code produces an undefined function error:


var s='function test(){return 1;}'; //A function definition statement
function demo2(){
    eval(s);
}
demo2();
alert(test()); //->error:test is not defined

This is because the test function is defined in local space, which is accessible inside demo2, but not outside.

Share: parse the attention points in JSON with Js eval
In JS, the JSON string is parsed into JSON data format in two ways:

One is to use the eval() function.

2. Use the Function object for return parsing.

The eval function is used for parsing and jquery's each method is used for traversal

The method of parsing JSON data with jquery, as the transmission pair of jquery asynchronous request, the result returned by jquery after the request is JSON object, here is considered to be the form of string returned by the server in the form of JSON, the use of JSONObject and other plug-ins encapsulated JSON object, and this is much the same, this is no longer explained.
The JSON string set is first shown here, and the string set is as follows:


var data=" 
{ 
root: 
[ 
{name:'1',value:'0'}, 
{name:'6101',value:' The Beijing municipal '}, 
{name:'6102',value:' tianjin '}, 
{name:'6103',value:' Shanghai '}, 
{name:'6104',value:' chongqing '}, 
{name:'6105',value:' weinan '}, 
{name:'6106',value:' Yan 'an '}, 
{name:'6107',value:' Grassland, '}, 
{name:'6108',value:' Yulin city '}, 
{name:'6109',value:' Ankang municipality '}, 
{name:'6110',value:' shangluo '} 
]
}"; 

Based on the data types obtained asynchronously by jquery -- json objects and strings, this paper introduces the result processing methods obtained in two ways.

1. If the JSON string returned by the server is not typed or accepted as a string by the jquery asynchronous request, it needs to be objectized once, either by placing the string in eval() and executing it once. This method is also suitable for the common javascript method to obtain json objects, the following examples:

Var dataObj = eval (" (" + data + ") "); // converted to json objects

"(" ("+data+")"); / / "?

Here's why: eval itself is a problem. Since json starts and ends with "{}," it is treated as a block of statements in JS, so it must be forced into an expression.

The purpose of the parentheses is to force the eval function to work with JavaScript code by forcing the expression inside the parentheses to be an object, rather than being executed as a statement. For example, if the object literal {} is not enclosed, then eval recognizes the braces as the start and end of JavaScript blocks, and {} is considered an empty statement. So the following two execution results are different:


alert(eval("{}"); // return undefined
alert(eval("({})");// return object[Object]

For this type of writing, in JS, you can see it all over the place.

Such as: (function () {} ();   Wait while doing closure operations.


alert(dataObj.root.length);//Output the number of child objects of root
$.each(dataObj.root,fucntion(idx,item){ 
if(idx==0){ 
return true; 
} 
//Output the name and value of each root child object
alert("name:"+item.name+",value:"+item.value); 
}) 

Note: for a normal js generated json object, just replace the $.each() method with a for statement, and the rest remains the same.

2. For the server returns a JSON string, if the jquery asynchronous request will type (generally) for this configuration attribute set to "JSON", or use $. GetJSON () method to obtain the server returns, so there is no need for the eval () method, because this time the result is a JSON object, simply call the object can be directly, in this to $. GetJSON method for example data processing methods:


$.getJSON("http://www.xx.cn/",{param:"gaoyusi"},function(data){ 
//The data returned here is already a json object
//The following other operations are the same as the first case
$.each(data.root,function(idx,item){ 
if(idx==0){ 
return true;//Countinue returns false as a break
} 
alert("name:"+item.name+",value:"+item.value); 
}); 
}); 

It is important to note that the eval() method in approach 1 executes the string (possibly a js script) dynamically, which can easily cause security problems for the system. So you can use third-party client-side scripting libraries that circumvent eval(), such as JSON in JavaScript, which provides a script library of up to 3k.

The second way of parsing is to use the Function object, which is typically used to parse return data such as success under AJAX methods in JQUERY


var json='{"name":"CJ","age":18}';
data =(new Function("","return "+json))();


At this point, the data is one that will be parsed into a json object


Related articles: