How JavaScript transforms and parses JSON

Source: Internet
Author: User

In JavaScript, the JSON string is parsed into a JSON data format, typically in two ways:

    • One for using the eval () function.
    • Use a Function object for return parsing. Jinyun County Foreign Experts Bureau
Use the Eval function to parse, jquery's each method to traverse

Using jquery to parse JSON data as a transport object for jquery asynchronous requests, the result of the jquery request is the JSON object, which is all about the server returning the form of a string in JSON form. For JSON objects that are encapsulated with plug-ins such as Jsonobject, this is also the same thing, and is no longer explained here.

Here we first give a set of JSON strings, the string set as follows:

01 vardata="
02 {
03 root:
04 [
05     {name:‘1‘,value:‘0‘},
06     {name:‘6101‘,value:‘北京市‘},
07     {name:‘6102‘,value:‘天津市‘},
08     {name:‘6103‘,value:‘上海市‘},
09     {name:‘6104‘,value:‘重庆市‘},
10 ]
11 }";

This is based on the data type obtained by jquery asynchronously,--json object and string, and describes how the results are handled in two ways.

Eval ()

For a JSON string returned by the server, if the jquery asynchronous request does not make a type description, or is accepted as a string, then an object processing is required, either in a cumbersome way or by placing the string in eval (). This is also a good way to get JSON objects in a normal Javascipt way, as illustrated below:

1 // 转换为json对象
2 vardataObj=eval("("+data+")");

Why to Eval here to add ("(" +data+ ")"); It?

The reason is that eval itself is a problem. Since JSON starts and ends in the form of "{}", in JS, it is treated as a block of statements, so it must be coerced into an expression.

The purpose of the parentheses is to force the Eval function to force the expression in parentheses to be converted to an object while processing the JavaScript code, rather than being executed as a statement (statement). For example, if the object literal {} is not enclosed, then eval will recognize the curly brace as the start and end tag of the JavaScript block, and {} will be considered an empty statement. So the following two execution results are different:

1 // return undefined
2 alert(eval("{}");
3 // return object[Object]
4 alert(eval("({})");

For this kind of writing, in JS, you can see everywhere. such as: (function ()) {} (); Do the closure operation and so on.

1 //输出root的子对象数量
2 alert(dataObj.root.length);
3 $.each(dataObj.root,fucntion(idx,item){
4     if(idx==0){
5         returntrue;
6     }
7     //输出每个root子对象的名称和值
8     alert("name:"+item.name+",value:"+item.value);
9 })

For a generic JS-generated JSON object, you only need to replace the $.each () method with the For statement, and the other is unchanged.

JSON string returned by the server

For the JSON string returned by the server, if the jquery asynchronous request sets the type (typically this configuration property) to "JSON", or the $.getjson () method is used to get the server back, then the eval () method is not required. Because the result is already a JSON object, just call the object directly, here $.getjson method as an example to illustrate the data processing method:

01 $.getJSON("http://www.phpzixue.cn/",{param:"gaoyusi"},function(data){
02     //此处返回的data已经是json对象
03     //以下其他操作同第一种情况
04     $.each(data.root,function(idx,item){
05         if(idx==0){
06             //同countinue,返回false同break
07             returntrue;
08         }
09         alert("name:"+item.name+",value:"+item.value);
10     });
11 });

In particular, it is important to note that the eval () method in mode 1 is the dynamic execution of strings (possibly JS scripts), which can easily cause system security problems. So you can use some third-party client script libraries that circumvent eval (), such as JSON in JavaScript, which provides a script library of no more than 3k.

The second parsing method is to use the function object to complete, its typical application is in jquery in the Ajax method of success and so on the return data of the parsing.

View Source print?
1 varjson=‘{"name":"CJ","age":18}‘;
2
3 data =(newFunction("","return "+json))();

The data at this point is the one that will parse into a JSON object.

How JavaScript transforms and parses JSON

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.