More detailed code for JavaScript parsing JSON _json

Source: Internet
Author: User
Tags eval in python

The rule of JSON is simple: an object is an unordered set of ' name/value pairs '. An object begins with "{" (opening parenthesis), and "}" (closing parenthesis) ends. Each "name" is followed by a ":" (a colon), and the ' name/value ' pair is separated by a ', ' (comma). Specific details Reference http://www.json.org/json-zh.html

For a simple example:

JS Code

Copy 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 represents a user object that has attributes such as username, age, info, and address.

You can also use JSON to simply modify the data, and modify the example above

JS Code
Copy 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 a json.js package that is introduced into the http://www.json.org/json.js and then can be converted to JSON data simply by using object.tojsonstring ().

JS Code
Copy 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 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 Code code as follows:

function Myeval () {
var str = ' {' name ': ' Violet ', ' occupation ': ' character '} ';
var obj = Str.parsejson ();
Alert (obj.tojsonstring ());
}

Below, use prototype to write a JSON Ajax example.

Write a servlet first (my name is Servlet.ajax.JSONTest1.java) and write a sentence.

Java code

Response.getwriter (). Print ("{\ name\": \ "violet\", \ "occupation\": \ "Character\"} ");
And then write an AJAX request in the page.

JS Code
Copy 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);
}

Prototype-1.5.1.js provides a method of JSON, String.evaljson (), you can modify the above method without using Json.js

JS Code
Copy 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 API is also very simple, here's an example

Fill in the request parameters in JavaScript

JS Code
Copy 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 can simply generate Jsonobject and parse, modifying the servlet Add JSON processing (to use Json.jar)

Java code
Copy Code code 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 JSON strings and modify the servlet

Java code
Copy Code code 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
Copy Code code 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

Using JSON
JSON, also known as JavaScript Object notation, is a lightweight syntax for describing data. JSON is elegant because it is a subset of the JavaScript language. Next you'll see why it's so important. First, compare the JSON and XML syntax.

Both JSON and XML use structured methods to describe the data. For example, an address book application can provide a Web service to generate an address Card in XML format:
Copy 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>
Type= ' work ' pref= ' 1 ' >+1 214 555 1212</tel> <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 Code code 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 that are similar to XML. JSON is also text-based, and so is XML. Both use Unicode. JSON and XML are easy to read. Subjectively, JSON is clearer and less redundant. The JSON web site is a strict description of the JSON syntax, and this is the way it is now. It's really a simple little language! XML is really good for tagging documents, but JSON is the ideal format for data interaction. Each JSON document describes an object that contains: nested objects, arrays, strings, numbers, Boolean values, or null values.

In these address Card example codes, the JSON version is lighter, takes up only 682 bytes of space, and the XML version requires 744 bytes of space. Although this is not a considerable savings. And the real benefit comes from the parsing process.

XML vs. JSON: status loss
By using the XMLHttpRequest object, you can get XML and JSON files from your AJAX-based applications. Typically, the interaction code is as follows:
Copy Code code 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, you provide a processor function (MyHandler function) that is called multiple times to provide you with an opportunity to terminate the transaction prematurely and update the progress bar. Typically, it works only after the Web request is completed: You can then use the returned data.

To handle an XML version of the Address card data, the MyHandler code is as follows:
Copy Code code as follows:

function MyHandler () {
if (req.readystate = = 4/*complete*/) {
Update address field in a form with the 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 is worth noting that you do not have to parse the XML document: The XMLHttpRequest object is automatically parsed and the DOM tree in the Responsexml is 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 to find it. You can then call getElementsByTagName again to find the first address element in the address section. This gets 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 the form field.

It's really not a simple job, now, use JSON and try again:
Copy 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 invoking the Eval function. Parsing JSON requires only one line! In addition, manipulating objects in JSON is like manipulating other JavaScript objects. This is obviously easier to manipulate than through a 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 a home address object
Card.fullname is the name of the card, "Sean Kelly."
If you look more closely, you may find that there is at least one element in the XML format for Chinese files, card. This doesn't exist in JSON, why? Presumably, if you're developing JavaScript to access Web services, you already know what you want. However, you can use this in JSON:
{"card": {"FullName": ...}}
With this technique, your JSON file is always started with an object with a single named attribute that identifies the object's kind.

is JSON fast and reliable?
JSON provides lightweight small documents, and JSON is easier to use in JavaScript. XMLHttpRequest automatically parses XML documents for you, and you have to parse JSON files manually, but is parsing json slower than parsing XML? The author uses XMLHttpRequest to parse XML and parse JSON with thousands of repeated tests, and the result is that parsing json is 10 times times faster than XML! When you look at Ajax as a desktop application, speed is the most important factor, and obviously, JSON is better.

Of course, you can't always control the server side to generate data for AJAX programs. You can also use a third-party server instead of a server to provide XML-formatted output. And if the server just provides JSON, can you be sure you really want to use it?

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

When it comes to parsing, Python enthusiasts may notice that JSON is not just a subset of JavaScript, it's a subset of Python. You can execute JSON directly in Python, or use secure JSON resolution instead. The json.org Web site lists many common JSON parsers.

Server-side JSON
Up until now, you may have focused on using JSON in an AJAX-based Web application running in a client's browser. Naturally, first of all, JSON-formatted data must be generated on the server side. Fortunately, it is fairly straightforward 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, the business Web service provider has noted the JSON. Yahoo has recently created a number of JSON based Web services. Many of Yahoo's search services, fulfillment programs, del.icio.us, and highway Traffic services also support JSON output. There is no doubt that other major Web service providers will also be added to the support of JSON.

Summarize
The smart thing about JSON is that it's a subset of JavaScript and python that makes it easier to use and provides efficient data interaction for Ajax. It is faster to parse and easier to use than XML. JSON is becoming the strongest sound of Web 2.0 now. Every developer, whether 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, 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.