How JavaScript handles parsing JSON data in detail

Source: Internet
Author: User

JSON (JavaScript Object Notation) is a simple data format that is lighter than XML. JSON is a native JavaScript format, which means that working with 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 "{" (opening parenthesis) and "}" (the closing parenthesis) ends. Each "name" is followed by a ":" (colon); "' Name/value ' pair ' is separated by", "(comma). Specific details refer to http://www.json.org/json-zh.html

To give a simple example:

JS Code

function Showjson () {    var user =    {    "username": "Andy",    "age": +,    "info": {"tel": " 123456 "," cellphone ":" 98765 "},    " address ":    [    {" City ":" Beijing "," postcode ":" 222333 "},    {" CIT    Y ":" 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, address, and so on.

You can also use JSON to simply modify the data, modify the above 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"}    ]& nbsp;   }     alert (user.username);     alert (user.ag e);     alert (user.info.cellphone);     alert (user.address[0].city);      alert (user.address[0].postcode);     user.username = "Tom";  &n bsp;   alert (user.username);    }   

JSON provides a json.js package that, after downloading Http://www.json.org/json.js, introduces it and then simply converts it to JSON data using object.tojsonstring ().

JS Code

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

function Myeval () {    var str = ' {' name ': ' Violet ', ' occupation ': ' character '} ';        var obj = eval (' (' + str + ') ');        alert (obj.tojsonstring ());    }

or use the Parsejson () method

JS Code

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

Use prototype to write a JSON example of Ajax.

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

Java code

Response.getwriter (). Print ("{\" name\ ": \" violet\ ", \" occupation\ ": \" Character\ "}");

And then write an AJAX request on the page.

JS Code

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 the JSON method, String.evaljson (), can not use json.js, modify the above method

JS Code

function Jsonresponse (originalrequest) {    alert (originalrequest.responsetext);        var myobj = OriginalRequest.responseText.evalJSON (true);        alert (myobj.name);    }

JSON also provides Java's Jar package Http://www.json.org/java/index.html API is also very simple, here is an example

Fill in the request parameters in JavaScript

JS Code

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,    onCo    Mplete:jsonresponse    }    );    }

Using the JSON request string, you can easily generate Jsonobject and parse, modify the servlet to add JSON processing (to use Json.jar)

Java code

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

private void Doservice (HttpServletRequest request, httpservletresponse response) throws IOException {      String s3 = Request.getparameter ("car");     try {     Jsono Bject jsonobj = new Jsonobject (S3);     System.out.println (jsonobj.getstring ("model"));  & nbsp;   System.out.println (Jsonobj.getint ("Year"));    } catch (Jsonexception e) {&NB sp;    e.printstacktrace ();    }     JSONObject Resul Tjson = new Jsonobject ();     try {     resultjson.append ("name", "Violet") & nbsp;   . 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 function jsonresponse (originalrequest) {  &NB sp;  alert (originalrequest.responsetext);     var myobj = OriginalRequest.responseText.eva Ljson (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

How JavaScript handles parsing JSON data in detail

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.