Parse JSON and XML in JS

Source: Internet
Author: User

When writing Ajax, it is often necessary to parse a string returned from the server. Here we will briefly introduce two formats of characters returned by the server and the parsing methods of Js for them.

I. JSON

JavaScript Object Notation (JavaScript Object Notation) is a string that is combined by declaring objects in Js.
JS can define objects as follows:

VaR OBJ =
{
ID: 2 ,
Name: ' N '
};

In this way, the object obj is defined. It has two common attributes: ID and name. You can directly access its attribute values using obj. Id.

When obtaining data from the server, there is usually more than one object, which requires an array of objects. The array of objects in JS can be defined using [], as shown below:

VaR Objs = [{ID: 1 , Name: ' N_1 ' }, {ID: 2 , Name: ' N_2 ' }];
Alert (objs [ 0 ]. ID );

In this way, the object array objs is defined. It contains two objects and can be accessed using indexes. For example, objs [0] Will reference the first object.
Here you may have thought about the format of the string returned by the server, but the string is a string after all, and we need to convert it to a variable that can be operated by Js.
This uses the eval function. See the following example:

VaR Objs = Eval ( " [{ID: 1, name: 'n' _ 1'}, {ID: 2, name: 'n' _ 2'}] " );
Alert (objs [ 0 ]. ID ); // Return 1 All right, on the server side, you only need to use the format [{ID: 1, name: 'n' _ 1'}, {ID: 2, Name: 'n' _ 2'}] returns a string,
The client can use eval () to execute the returned string to obtain the object array. The following is a simple example using Ajax. Create a new website and add a general process under the root directory Program (Getjson. ashx ), Code As follows: Getjson. ashx
<% @ Webhandler Language = " C # " Class = " Getjson "   %>

UsingSystem;
UsingSystem. Web;

Public ClassGetjson: ihttphandler {

Public VoidProcessrequest (httpcontext context ){

String Str =   " [{ID: 1, name: 'n' _ 1'}, {ID: 2, name: 'n' _ 2'}] " ;

Context. response. contenttype =   " Text/plain " ;
Context. response. Write (STR );
}
 
Public   Bool Isreusable {
Get {
Return   False ;
}
}

}

Add the test script to the default. aspx file:

< Script Type = " Text/JavaScript " >
Function Getjson (){
// The test passes in IE7, and new activexobject ("msxml2.xmlhttp. 6.0") must be created in IE6 ")
VaR Request =   New XMLHttpRequest ();

Request. Open ( ' Get ' , ' Getjson. ashx ' );
Request. onreadystatechange =   Function (){
If (Request. readystate =   4   && Request. Status =   200 ){
VaR Objs = Eval (request. responsetext );
Alert (objs. Length ); // 2
Alert (objs [ 0 ]. ID ); // 1
Alert (objs [ 1 ]. Name ); // 'N' _ 2'
}
}
Request. Send ( Null );
}
< / SCRIPT>

Add a test button to view the effect:

< Input Type = "Button" Value = "Getjson" Onclick = "Getjson ();"   /> Ii. xml JS parses XML based on Dom. If you are familiar with HTML Dom, it is no longer difficult to parse XML. Note: In Firefox, the parser does not ignore spaces, so spaces between elements are considered as a node like ff.
However, when we splice XML with a program, there is usually no space between nodes. Add a new general handler (getxml. ashx) in the root directory. The Code is as follows: Getxml. ashx
<% @ Webhandler Language = " C # " Class = " Getxml "   %>

UsingSystem;
UsingSystem. Web;

Public ClassGetxml: ihttphandler {

Public VoidProcessrequest (httpcontext context ){

System. Text. stringbuilder sb =   New System. Text. stringbuilder ( " <? XML version = '1. 0'?> <Persons> " );
String Temp =   " <Person> <ID >{0} </ID> <name >{1} </Name> </person> " ;
SB. appendformat (temp, 1 , " N_1 " );
SB. appendformat (temp, 2 , " N_2 " );
SB. append ( " </Persons> " );

Context. response. contenttype =   " Text/XML " ;
Context. response. Write (sb. tostring ());
}
 
Public   Bool Isreusable {
Get {
Return   False ;
}
}

}

Add the following script on the default. aspx page:

Function Getxml (){
// The test passes in IE7, and new activexobject ("msxml2.xmlhttp. 6.0") must be created in IE6 ")
VaR Request =   New XMLHttpRequest ();

Request. Open ( ' Get ' , ' Getxml. ashx ' );
Request. onreadystatechange =   Function (){
If (Request. readystate =   4   && Request. Status =   200 ){
VaR Xmldoc = Request. responsexml;
VaR Root = Xmldoc.doc umentelement;
VaR Elements = Root. getelementsbytagname ( " Person " );
Alert (elements. Length ); // 2
// Elements [0]. firstchild references the ID node of the first person Node
// Elements [0]. firstchild. firstchild references to the text node of the ID Node
// Because the text node is the first child node of the Element Node
Alert (elements [ 0 ]. Firstchild. firstchild. nodevalue ); // 1
Alert (elements [ 1 ]. Lastchild. firstchild. nodevalue ); // 'N' _ 2'
}
}
Request. Send ( Null );
} Notes:VaR Root = Xmldoc.doc umentelement; In order to eliminate the compatibility between IE6 and other browsers, the request. responsexml. getelementsbytagname ("Person"); Add test button:

< Input Type = "Button" Value = "Getxml" Onclick = "Getxml ();"   /> Conclusion: It is easy to see from the code that parsing JSON is relatively intuitive, and there are few strings to be transmitted in the network. The browser compatibility issue does not need to be considered during the parsing process.
JSON is more suitable for lightweight data interaction. XML has more features than JSON, such as namespaces and more node types. Sample source file

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.