JSON (JavaScript Object Notation) is a simple data format that is more lightweight than xml. JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.
The rules of JSON are simple: an object is an unordered "name / value" pair. An object begins with "{" (left parenthesis) and ends with "}" (right parenthesis). Each "name" is followed by a ":" (colon); "name / value" pairs are separated by "," (comma). For details, please refer to http://www.json.org/json-zh.html
To give a simple example:
js code
Copy the code code 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 means a user object with attributes such as username, age, info, address.
You can also use JSON to simply modify the data. Modify the above example
js code
Copy the code code 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. After downloading http://www.json.org/json.js, import it and then simply use object.toJSONString () to convert it into JSON data.
js code
Copy the code code 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 Object
js code
Copy the code code as follows:
function myEval () {
var str = '{"name": "Violet", "occupation": "character"}';
var obj = eval ('(' + str + ')');
alert (obj.toJSONString ());
}
Or use the parseJSON () method
js code
Copy the code code as follows:
function myEval () {
var str = '{"name": "Violet", "occupation": "character"}';
var obj = str.parseJSON ();
alert (obj.toJSONString ());
}
Let's write a JSON Ajax example using prototype.
First write a servlet (mine is servlet.ajax.JSONTest1.java) and write a sentence
java code
Copy the code code as follows:
response.getWriter (). print ("{/" name / ": /" Violet / ", /" occupation / ": /" character / "}");
Then write an ajax request in the page
js code
Copy the code code 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);
}
JSON method is provided in prototype-1.5.1.js, String.evalJSON (), you can modify the above method without using json.js
js code
Copy the code code as follows:
function jsonResponse (originalRequest) {
alert (originalRequest.responseText);
var myobj = originalRequest.responseText.evalJSON (true);
alert (myobj.name);
}
JSON also provides a java jar package http://www.json.org/java/index.html The API is also very simple, here is an example
Fill request parameters in javascript
js code
Copy the code code 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
}
);
}
Using the JSON request string, you can simply generate a JSONObject and parse it, modify the servlet to add JSON processing (to use json.jar)
Use JSON
JSON, or JavaScript Object Notation, is a lightweight syntax for describing data. JSON is elegant because it is a subset of the JavaScript language. Next you will see why it is so important. First, let's compare the JSON and XML syntax.
Both JSON and XML use structured methods to describe data. For example, an address book application can provide a web service for generating address cards in XML format:
Copy the code code as follows:
<? xml version = '1.0' encoding = 'UTF-8'?>
<card>
<fullname> Sean Kelly </ fullname>
<org>
SK Consulting </ org>
<emailaddrs>
<address type = 'work'> kelly@seankelly.biz </ address>
<address type = 'home' pref = '1'> kelly@seankelly.tv </ address>
</ emailaddrs>
<telephones>
<tel type = 'work' pref = '1'> + 1 214 555 1212 </ tel>
<tel type = 'fax'> + 1 214 555 1213 </ tel>
<tel type = 'mobile'> + 1 214 555 1214 </ tel>
</ telephones>
<addresses>
<address type = 'work' format = 'us'> 1234 Main St
Springfield, TX 78080-1216 </ address>
<address type = 'home' format = 'us'> 5678 Main St
Springfield, TX 78080-1316 </ address>
</ addresses>
<urls>
<address type = 'work'> http://seankelly.biz/ </ address>
<address type = 'home'> http://seankelly.tv/ </ address>
</ urls>
</ card>
Using JSON, the form is as follows:
Copy the code code as follows:
As you can see, JSON has structured nested data elements, which is similar to XML. JSON is also text-based, as is XML. Both use Unicode. Both JSON and XML are easy to read. Subjectively, JSON is clearer and less redundant. The JSON WEB site strictly describes the JSON syntax, and this is currently the case. It is indeed a simple little language! XML is indeed suitable for tagging documents, but JSON is the ideal format for data interaction. Each JSON document describes one such object, which contains: nested objects, arrays, strings, numbers, booleans, or null values.
In these address card example code, the JSON version is more lightweight and only takes up 682 bytes of space, while the XML version requires 744 bytes of space. Although this is not a considerable saving. The practical benefit comes from the parsing process.
XML vs. JSON: loss of status
By using the XMLHttpRequest object, you can get XML and JSON files from your AJAX-based application. Typically, the interaction code is as follows:
Copy the code code as follows:
As a response from the web server, the handler function (myHandler function) you provided is called multiple times, providing you with opportunities to terminate the transaction early and update the progress bar. Normally, it only works after the web request is completed: then you can use the returned data.
In order to process the XML version of the address card data, the code of myHandler is as follows:
Copy the code code 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 ('addresses') [0];
var firstAddr = addrsElem.getElementsByTagName ('address') [0];
var addrText = fistAddr.firstChild;
var addrValue = addrText.nodeValue;
addrField.value = addrValue;
}
}
It's important to note that you don't have to parse the XML document: the XMLHttpRequest object parses it automatically and makes the DOM tree in responseXML available. By using the responseXML property, you can call the getElementsByTagName method to find the address part of the document, and you can also use the first one to find it. You can then call getElementsByTagName again to find the first address element in the address section. This takes the first DOM child node of the document, which is a text node, and gets the value of the node, which is the street address you want. Finally, you can display the results in a form field.
It's really not a simple task. Now, try again using JSON:
Copy the code code 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 JavaScript's own compiler to parse it by calling the eval function. It only takes one line to parse JSON! In addition, manipulating objects in JSON is just like manipulating other JavaScript objects. This is obviously simpler than manipulating 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 the card, "Sean Kelly"
If you look more closely, you may find that documents in XML format have at least one element, card. This doesn't exist in JSON, why? Presumably, if you are developing JavaScript to access Web services, you already know what you want. However, you can use it like this in JSON:
{"card": {"fullname": ...}}
Using this technique, your JSON file always starts with an object with a single named attribute that identifies the kind of object.
Is JSON fast and reliable?
JSON provides lightweight small documents, and JSON is easier to use in JavaScript. XMLHttpRequest automatically parses the XML document for you, and you have to parse the JSON file manually, but is parsing JSON slower than parsing XML? The author passed thousands of repeated tests, using XMLHttpRequest to parse XML and parse JSON, and the result is that parsing JSON is 10 times faster than XML! When looking at AJAX as a desktop application, speed is the most important factor. Obviously, JSON is better.
Of course, you can't always control the server to generate data for AJAX programs. You can also use a third-party server instead of the server to provide XML-formatted output. And, if the server happens to provide JSON, can you be sure you really want to use it?
It is worth noting in the code that you pass the response text directly into eval. If you control the server, you can do this. If not, a malicious server can cause your browser to perform dangerous operations. In such cases, you'd better use code written in JavaScript to parse JSON. Fortunately, this is already there.
When it comes to parsing, Python enthusiasts may notice that JSON is not just a subset of JavaScript, it is also a subset of Python. You can execute JSON directly in Python or use secure JSON parsing instead. The JSON.org website lists many common JSON parsers.
Server-side JSON
Until now, you may have focused on using JSON in AJAX-based web applications running in client browsers. Naturally, first of all, data in JSON format must be generated on the server side. Fortunately, creating JSON or converting other existing data into JSON is fairly simple. Some web application frameworks, such as TurboGears, automatically include support for JSON output.
In addition, commercial web service providers have also noticed JSON. Yahoo has 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 join the support for JSON.
to sum up
The cleverness of JSON is that it 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 sound of "Web 2.0" now. Every developer, whether it's a standard desktop application or a web application, is increasingly aware of its simplicity and convenience. I hope you can appreciate the fun of applying JSON to buzzword-compliant, Web-2.0-based, AJAX-enabled, agile development.
PS: Regarding json operation, here are a few more practical json online tools for your reference:
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.