JSON (JavaScript Object Notation) is a simple data format that is lighter than xml. JSON is a JavaScript native format, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.
The rules of JSON are simple: an object is an unordered collection of "'name/value' pairs'. An object starts with "{" (open bracket) and ends with "}" (close bracket). Each "name" is followed by a ":" (colon); "'name/value' pair" is separated by "," (comma). Specific details reference/
Let's give a simple example:
js code
function showJSON() {
var user =
{
"username":"andy",
"age":20,
"info": { "tel": "123456", "cellphone": "98765"},
"address":
[
{"city":"beijing","postcode":"222333"},
{"city":"newyork","postcode":"555666"}
]
}
alert();
alert();
alert();
alert([0].city);
alert([0].postcode);
}
This means that a user object has username, age, info, address and other properties.
You can also use JSON to simply modify the data and modify the above examples.
js code
function showJSON() {
var user =
{
"username":"andy",
"age":20,
"info": { "tel": "123456", "cellphone": "98765"},
"address":
[
{"city":"beijing","postcode":"222333"},
{"city":"newyork","postcode":"555666"}
]
}
alert();
alert();
alert();
alert([0].city);
alert([0].postcode);
= "Tom";
alert();
}
JSON provides packages, after downloading /, it can be imported and then simply converted to JSON data using().
js code
function showCar() {
var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow");
alert(());
}
function Car(make, model, year, color) {
= make;
= model;
= year;
= color;
}
You can use eval to convert JSON characters to Object
js code
function myEval() {
var str = '{ "name": "Violet", "occupation": "character" }';
var obj = eval('(' + str + ')');
alert(());
}
Or use the parseJSON() method
js code
function myEval() {
var str = '{ "name": "Violet", "occupation": "character" }';
var obj = ();
alert(());
}
Below is ajax example of JSON using prototype.
Write a servlet first (mine is.) and write a sentence
java code
().print("{ /"name/": /"Violet/", /"occupation/": /"character/" }");
Write a request for ajax on the page
js code
function sendRequest() {
var url = "/MyWebApp/JSONTest1";
var mailAjax = new (
url,
{
method: 'get',
onComplete: jsonResponse
}
);
}
function jsonResponse(originalRequest) {
alert();
var myobj = ();
alert();
}
Prototype-1.5. provides JSON methods, (), which can be used without using, modify the above method
js code
function jsonResponse(originalRequest) {
alert();
var myobj = (true);
alert();
}
JSON also provides the java jar package /java/ API which is also very simple. Here is an example
Fill in request parameters in javascript
js code
function sendRequest() {
var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow");
var pars = "car=" + ();
var url = "/MyWebApp/JSONTest1";
var mailAjax = new (
url,
{
method: 'get',
parameters: pars,
onComplete: jsonResponse
}
);
}
Using JSON request strings can simply generate JSONObject and parse it, modify the servlet to add JSON (to be used)
java code
private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException {
String s3 = ("car");
try {
JSONObject jsonObj = new JSONObject(s3);
(("model"));
(("year"));
} catch (JSONException e) {
();
}
().print("{ /"name/": /"Violet/", /"occupation/": /"character/" }");
}
You can also use JSONObject to generate JSON strings and modify servlets.
java code
private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException {
String s3 = ("car");
try {
JSONObject jsonObj = new JSONObject(s3);
(("model"));
(("year"));
} catch (JSONException e) {
();
}
JSONObject resultJSON = new JSONObject();
try {
("name", "Violet")
.append("occupation", "developer")
.append("age", new Integer(22));
(());
} catch (JSONException e) {
();
}
().print(());
}
js code
function jsonResponse(originalRequest) {
alert();
var myobj = (true);
alert();
alert();
}
refer to
/
/Jkallen/archive/2006/03/28/
/
/learn/json
/java/
/developerworks/cn/web/wa-ajaxintro10/
Using JSON
JSON, 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 JSON and XML syntax.
Both JSON and XML describe data using structured methods. For example, an address book application may provide a web service for generating address cards in XML format:
<?xml version='1.0' encoding='UTF-8'?>
<card>
<fullname>Sean Kelly</fullname>
<org>SK Consulting</org>
<emailaddrs>
<address type='work'>kelly@</address>
<address type='home' pref='1'>kelly@</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'>/</address>
<address type='home'>/</address>
</urls>
</card>
Use JSON, the form is as follows:
{
"fullname": "Sean Kelly",
"org": "SK Consulting",
"emailaddrs": [
{"type": "work", "value": "kelly@"},
{"type": "home", "pref": 1, "value": "kelly@"}
],
"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": "/"},
{"type": "home", "value": "/"}
]
}
As you can see, JSON has structured nested data elements, which is similar to XML. JSON is also text-based, and so 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, which is what it is currently. It is indeed a simple little language! XML is indeed suitable for tagging documents, but JSON is an ideal format for data interaction. Each JSON document describes an object containing: nested objects, arrays, strings, numbers, booleans, or null values.
In these address card example codes, the JSON version is lighter, taking up only 682 bytes of space, while the XML version requires 744 bytes of space. Although this is not a considerable saving. The actual benefits come from the analytical 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 interactive code is as follows:
var req = new XMLHttpRequest();
("GET", "http://localhost/addr?cardID=32", /*async*/true);
= myHandler;
(/*no params*/null);
As a WEB server response, the processor function (myHandler function) you provide is called multiple times, providing you with opportunities to terminate transactions in advance, update progress bars, etc. Usually, it only works after the web request is completed: then you can use the returned data.
In order to process the XML version of address card data, the code of myHandler is as follows:
function myHandler() {
if ( == 4 /*complete*/) {
// Update address field in a form with first street address
var addrField = ('addr');
var root = ;
var addrsElem = ('addresses')[0];
var firstAddr = ('address')[0];
var addrText = ;
var addrValue = ;
= addrValue;
}
}
It is worth noting that you don't have to parse XML documents: the XMLHttpRequest object is automatically parsed 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. Then, you can call getElementsByTagName again to find the first address element in the address part. This takes the first DOM child node of the document, which is a text node, and obtains the value of the node, which is the street address you want. Finally, the results can be displayed in the form field.
It's not a simple job, now, try it again using JSON:
function myHandler() {
if ( == 4 /*complete*/) {
var addrField = ('addr');
var card = eval('(' + + ')');
= [0].value;
}
}
The first thing you do is parse the JSON response. However, because JSON is a subset of JavaScript, you can parse it using JavaScript's own compiler by calling the eval function. Only one line is required to parse JSON! Furthermore, manipulating objects in JSON is like manipulating other JavaScript objects. This is obviously simpler than manipulating through the DOM tree, for example:
[0].value is the first street address, "1234 Main Stb &"
[0].type is the address type, "work"
[1] is a home address object
It is the name of the card, "Sean Kelly"
If you look more closely, you may find that the document in XML format has at least one element and card. This does not exist in JSON, why? Probably, if you are developing JavaScript to access web services, you already know what you want to get. However, you can use it in JSON like this:
{"card": {"fullname": ...}}
Using this technique, your JSON file always starts with an object with a single named attribute that identifies the type of object.
Is JSON fast and reliable?
JSON provides lightweight small documentation, and JSON is easier to use in JavaScript. XMLHttpRequest automatically parses XML documents for you, and you also have to manually parse JSON files, but is parsing JSON slower than parsing XML? The author used XMLHttpRequest to parse XML and JSON through thousands of repeated tests, and the result was that parsing JSON was 10 times faster than XML! When viewing AJAX as a desktop application, speed is the most important factor, and it is obvious that JSON is better.
Of course, you can't always control the server side to generate data for the AJAX program. You can also use a third-party server to provide output in XML format instead of the server. And, if the server happens to provide JSON, are you sure you really want to use it?
It is worth noting in the code that you pass the response text directly into the eval. If you control the server, you can do this. If not, a malicious server can make your browser perform dangerous operations. In this case, you'd better use code written in JavaScript to parse JSON. Fortunately, this has already happened.
Speaking of 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 website lists many commonly used JSON parsers.
Server-side JSON
Until now, you may be focusing on using JSON on AJAX-based web applications running in the client browser. Naturally, first of all, data in JSON format must be generated on the server side. 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 have also noticed JSON. Yahoo has recently created many JSON-based web services. Yahoo's various search services, fulfillment plans, and highway transportation services also support JSON output. There is no doubt that other major WEB service providers will also be added to support for JSON.
Summarize
JSON's cleverness 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 voice for "Web 2.0". Every developer, whether it is a standard desktop application or a web application, is increasingly noticing its simplicity and convenience. I hope you can experience the fun of applying to JSON in buzzword- compliant, Web-2.0-based, AJAX-enabled, agile development.
PS: Regarding json operation, here are some practical json online tools for your reference:
Online JSON code verification, inspection, beautification and formatting tools:
http://tools./code/json
JSON online formatting tool:
http://tools./code/jsonformat
Online XML/JSON mutual conversion tool:
http://tools./code/xmljson
json code online formatting/beautification/compression/editing/converting tools:
http://tools./code/jsoncodeformat
Online json compression/escaping tools:
http://tools./code/json_yasuo_trans
C language style/HTML/CSS/json code formatting and beautification tools:
http://tools./code/ccode_html_css_json