JavaScript handles parsing JSON data process detailed _javascript tips

Source: Internet
Author: User

JSON (JavaScript Object notation) is a simple data format that is lighter than XML. JSON is the native format of JavaScript, which means that processing JSON data in JavaScript does not require any special APIs or toolkits.

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

function Showjson () {  
  var user =  
  {  
  "username": "Andy",  
  "age": "  
  Info": {"tel": "123456", "" Cellphone ":" 98765 "},  
  " address ":  
  [  
  {The 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

function Showjson () {  
  var user =  
  {  
  "username": "Andy",  
  "age": "  
  Info": {"tel": "123456", "" Cellphone ":" 98765 "},  
  " address ":  
  [  
  {The 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

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 ());  
  }

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

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

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

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

private void Doservice (HttpServletRequest request, httpservletresponse response) throws IOException {  
  String s3 = req Uest.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

 private void Doservice (HttpServletRequest request, httpservletresponse response) throws I  
  oexception {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 function Jsonresponse (originalrequest) {alert (originalrequest.responsetext);  
  var myobj = OriginalRequest.responseText.evalJSON (true);  
  alert (myobj.name);  
  alert (myobj.age); } 

The above content is to introduce Javascrip processing T parsing JSON data process, I hope to help.

Related Article

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.