Javascript-based json reading and writing _ javascript skills

Source: Internet
Author: User
JSON is a simple data format, which is lighter than xml. You do not need any special APIs or toolkit to process JSON data in JavaScript. The following is an example, you can refer to JSON (JavaScript Object Notation) as a simple data format, which is lighter than xml. JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.

JSON rules are simple: the object is an unordered set of 'name/value' pairs. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs. Detailed reference http://www.json.org/json-zh.html

A simple example:

Js Code

The Code is as follows:


Function showJSON (){

Var user =

{

"Username": "andy ",

"Age": 20,

"Info": {"tel": "123456", "cellphone": "98765 "},

"Address ":

[

{"City": "beijing", "postcode": "222333 "},

{"City": "newyork", "postcode": "555666 "}

]

}

Alert (user. username );

Alert (user. age );

Alert (user.info. cellphone );

Alert (user. address [0]. city );

Alert (user. address [0]. postcode );

}


This indicates that a user object has attributes such as username, age, info, and address.

You can also use JSON to modify the data.

Js Code

The Code is as follows:


Function showJSON (){

Var user =

{

"Username": "andy ",

"Age": 20,

"Info": {"tel": "123456", "cellphone": "98765 "},

"Address ":

[

{"City": "beijing", "postcode": "222333 "},

{"City": "newyork", "postcode": "555666 "}

]

}

Alert (user. username );

Alert (user. age );

Alert (user.info. cellphone );

Alert (user. address [0]. city );

Alert (user. address [0]. postcode );

User. username = "Tom ";

Alert (user. username );

}


JSON provides the json. js package, download the http://www.json.org/json.js, introduce it and then you can simply use object. toJSONString () to convert to JSON data.

Js Code

The Code is as follows:


Function showCar (){

Var carr = new Car ("Dodge", "Coronet R/T", 1968, "yellow ");

Alert (carr. toJSONString ());

}

Function Car (make, model, year, color ){

This. make = make;

This. model = model;

This. year = year;

This. color = color;

}


You can use eval to convert JSON characters to objects.

Js Code

The Code is as follows:


Function myEval (){

Var str = '{"name": "Violet", "occupation": "character "}';

Var obj = eval ('+ str + ')');

Alert (obj. toJSONString ());

}


Or use the parseJSON () method.

Js Code

The Code is as follows:


Function myEval (){

Var str = '{"name": "Violet", "occupation": "character "}';

Var obj = str. parseJSON ();

Alert (obj. toJSONString ());

}


The following uses prototype to write a JSON ajax example.

Write a servlet (My servlet. ajax. JSONTest1.java) to write a sentence.

Java code

The Code is as follows:


Response. getWriter (). print ("{/" name/":/" Violet/",/" occupation/":/" character /"}");


Then write an ajax request in the page.

Js Code

The Code is as follows:


Function sendRequest (){

Var url = "/MyWebApp/JSONTest1 ";

Var mailAjax = new Ajax. Request (

Url,

{

Method: 'get ',

OnComplete: jsonResponse

}

);

}

Function jsonResponse (originalRequest ){

Alert (originalRequest. responseText );

Var myobj = originalRequest. responseText. parseJSON ();

Alert (myobj. name );

}


The JSON method is provided in the prototype-1.5.1.js, String. evalJSON (), you can modify the above method without using json. js

Js Code

The Code is as follows:


Function jsonResponse (originalRequest ){

Alert (originalRequest. responseText );

Var myobj = originalRequest. responseText. evalJSON (true );

Alert (myobj. name );

}


JSON also provides java jar package http://www.json.org/java/index.html API is also very simple, the following example

Add Request Parameters in javascript

Js Code

The Code is as follows:


Function sendRequest (){

Var carr = new Car ("Dodge", "Coronet R/T", 1968, "yellow ");

Var pars = "car =" + carr. toJSONString ();

Var url = "/MyWebApp/JSONTest1 ";

Var mailAjax = new Ajax. Request (

Url,

{

Method: 'get ',

Parameters: pars,

OnComplete: jsonResponse

}

);

}


JSON request string can be used to generate and parse JSONObject, modify servlet to add JSON processing (json. jar is required)

Java code

The Code is as follows:


Private void doService (HttpServletRequest request, HttpServletResponse response) throws IOException {

String s3 = request. getParameter ("car ");

Try {

JSONObject jsonObj = new JSONObject (s3 );

System. out. println (jsonObj. getString ("model "));

System. out. println (jsonObj. getInt ("year "));

} Catch (JSONException e ){

E. printStackTrace ();

}

Response. getWriter (). print ("{/" name/":/" Violet/",/" occupation/":/" character /"}");

}


You can also use JSONObject to generate a JSON string and modify the servlet

Java code

The Code is as follows:


Private void doService (HttpServletRequest request, HttpServletResponse response) throws IOException {

String s3 = request. getParameter ("car ");

Try {

JSONObject jsonObj = new JSONObject (s3 );

System. out. println (jsonObj. getString ("model "));

System. out. println (jsonObj. getInt ("year "));

} Catch (JSONException e ){

E. printStackTrace ();

}

JSONObject resultJSON = new JSONObject ();

Try {

ResultJSON. append ("name", "Violet ")

. Append ("occupation", "developer ")

. Append ("age", new Integer (22 ));

System. out. println (resultJSON. toString ());

} Catch (JSONException e ){

E. printStackTrace ();

}

Response. getWriter (). print (resultJSON. toString ());

}


Js Code

The Code is as follows:


Function jsonResponse (originalRequest ){

Alert (originalRequest. responseText );

Var myobj = originalRequest. responseText. evalJSON (true );

Alert (myobj. name );

Alert (myobj. age );

}


Reference

Http://www.json.org/js.html

Http://www.blogjava.net/Jkallen/archive/2006/03/28/37905.html

Http://www.json.org/

Http://www.prototypejs.org/learn/json

Http://www.json.org/java/index.html

Http://www.ibm.com/developerworks/cn/web/wa-ajaxintro10/index.html

Use JSON
JSON, also known as JavaScript Object Notation, is a lightweight syntax that describes data. JSON is elegant because it is a subset of the JavaScript language. Next you will see why it is so important. First, compare the JSON and XML syntaxes.

Both JSON and XML use structured methods to describe data. For example, an address book application can provide web Services for generating Address Cards in XML format:

The Code is as follows:




Sean Kelly
SK Consulting

Kelly@seankelly.biz
Kelly@seankelly. TV


+ 1 214 555 1212
+ 1 214 555 1213
+ 1 214 555 1214


1234 Main St
Springfield, TX 78080-1216
5678 Main St
Springfield, TX 78080-1316


Http://seankelly.biz/
Http://seankelly. TV/



JSON format:

The Code is as follows:


{
"Fullname": "Sean Kelly ",
"Org": "SK Consulting ",
"Emailaddrs ":[
{"Type": "work", "value": "kelly@seankelly.biz "},
{"Type": "home", "pref": 1, "value": "kelly@seankelly. TV "}
],
"Telephones ":[
{"Type": "work", "pref": 1, "value": "+ 1 214 555 1212 "},
{"Type": "fax", "value": "+ 1 214 555 1213 "},
{"Type": "mobile", "value": "+ 1 214 555 1214 "}
],
"Addresses ":[
{"Type": "work", "format": "us ",
"Value": "1234 Main StnSpringfield, TX 78080-1216 "},
{"Type": "home", "format": "us ",
"Value": "5678 Main StnSpringfield, TX 78080-1316 "}
],
"Urls ":[
{"Type": "work", "value": "http://seankelly.biz /"},
{"Type": "home", "value": "http://seankelly. TV /"}
]
}


As you can see, JSON has structured nested data elements, which are similar to XML. JSON is also text-based, and XML is the same. Both use Unicode. JSON and XML are both easy to read. Subjectively, JSON is clearer and redundant. The json web site strictly describes the JSON syntax. This is the case currently. It is indeed a simple little language! XML is indeed suitable for marking documents, but JSON is an ideal format for data interaction. Each JSON document describes an object that contains nested objects, arrays, strings, numbers, Boolean values, or null values.

In the example code of these address cards, the JSON version is more lightweight and only occupies 682 bytes of space, while the XML version requires 744 bytes of space. Although this is not a considerable savings. The actual benefit comes from the parsing process.

XML comparison JSON: loss of status
By using the XMLHttpRequest object, you can obtain XML and JSON files from your AJAX-based applications. The interaction code is as follows:

The Code is as follows:


Var req = new XMLHttpRequest ();
Req. open ("GET", "http: // localhost/addr? CardID = 32 ",/* async */true );
Req. onreadystatechange = myHandler;
Req. send (/* no params */null );


As a WEB server response, your processor function (myHandler function) is called multiple times, providing you with the opportunity to terminate transactions and update progress bars in advance. Generally, it takes effect only after the web request is completed: At that time, you can use the returned data.

To process the address card data of the XML version, the myHandler code is as follows:

The Code is as follows:


Function myHandler (){
If (req. readyState = 4/* complete */){
// Update address field in a form with first street address
Var addrField = document. getElementById ('addr ');
Var root = req. responseXML;
Var addrsElem = root. getElementsByTagName ('address') [0];
Var firstAddr = addrsElem. getElementsByTagName ('address') [0];
Var addrText = fistAddr. firstChild;
Var addrValue = addrText. nodeValue;
AddrField. value = addrValue;
}
}


Note that you do not need to parse the XML document: the XMLHttpRequest object is automatically parsed and the DOM tree in responseXML is available. By using the responseXML attribute, you can call the getElementsByTagName method to find the document address. You can also use the first method to find the document address. Then, call getElementsByTagName again to find the first address element in the address section. This gets the first DOM sub-node of the document, which is a text node and obtains the value of the node. This is the street address you want. Finally, the results can be displayed in the form field.

It is really not a simple task. Now, try again with JSON:

The Code is as follows:


Function myHandler (){
If (req. readyState = 4/* complete */){
Var addrField = document. getElementById ('addr ');
Var card = eval ('+ req. responseText + ')');
AddrField. value = card. addresses [0]. value;
}
}


The first thing you do is parse the JSON response. However, because JSON is a subset of JavaScript, you can use the JavaScript compiler to parse it and call the eval function. Only one line is required for parsing JSON! In addition, manipulating objects in JSON is like manipulating other JavaScript objects. This is obviously more efficient than manipulating a simple ticket through the DOM tree, for example:
Card. addresses [0]. value is the first street address, "1234 Main Stb &"
Card. addresses [0]. type is the address type, "work"
Card. addresses [1] is the home address object
Card. fullname is the name of card, "Sean Kelly"
If you take a closer look, you may find that the document in XML format has at least one heel element, card. This does not exist in JSON. Why? Probably, if you are developing JavaScript to access Web services, you already know what you want. However, you can use the following in JSON:
{"Card": {"fullname ":...}}

With this technology, your JSON file always starts with an object with a single naming attribute, which identifies the object type.

Is JSON fast and reliable?

JSON Provides Lightweight small documents, and JSON is easier to use in JavaScript. XMLHttpRequest automatically parses the XML file for you, but you still need to manually parse the JSON file, but is it slower to parse the JSON file than to parse the XML file? After thousands of repeated tests, the author uses XMLHttpRequest to parse XML and JSON. The result is 10 times faster than XML! When AJAX is treated as a desktop application, speed is the most important factor. Obviously, JSON is better.

Of course, you cannot always control the server to generate data for AJAX programs. You can also use a third-party server to provide XML output instead of the server. In addition, if the server exactly provides JSON, are you sure you want to use it?

In the code, it is worth noting that you pass the response text directly to the eval. If you control the server, you can do this. If not, a malicious server can enable your browser to perform dangerous operations. In this case, you 'd better use the code written in JavaScript to parse JSON. Fortunately, this already exists.

Speaking of parsing, Python enthusiasts may note that JSON is not only a subset of JavaScript, but also a subset of Python. You can directly execute JSON in Python or use secure JSON resolution instead. The JSON.org website lists many common JSON parser.

Server-side JSON

Until now, you may focus on using JSON for AJAX-based web applications running in your browser. Naturally, data in JSON format must be generated on the server. Fortunately, it is quite simple to create JSON or convert other existing data into JSON. Some WEB application frameworks, such as TurboGears, automatically include support for JSON output.

In addition, commercial WEB service providers also noticed JSON. Yahoo recently created many JSON-based web Services. Yahoo's various search services, fulfillment plans, del. icio. us, and highway transportation services also support JSON output. There is no doubt that other major WEB service providers will also be added to support JSON.

Summary

JSON is a subset of JavaScript and Python, making it easier to use and providing efficient data interaction for AJAX. It parses faster and is easier to use than XML. JSON is becoming the strongest voice of "Web 2.0. Every developer, whether a standard desktop application or Web application, is increasingly aware of its simplicity and convenience. I hope you will have fun using JSON in buzzword-compliant, Web-2.0-based, AJAX-enabled, and agile development.

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.