Json operations using JS

Source: Internet
Author: User
JsonJSON (JavaScriptObjectNotation) is a simple data format, which is lighter than xml. JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript. JSON rules are simple: the object is an unordered set of 'name/value' pairs. One

JS operation Json

JSON (JavaScript Object Notation) is a simple data format, which is lighter than xml. JSON is a JavaScript native format, which means that no special API or toolkit is required to process JSON data in JavaScript.
JSON rules are simple: the object is an unordered set of 'name/value' pairs. An object starts with "{" (left parenthesis) and ends with "}" (right Parenthesis. Each "name" is followed by a ":" (colon); "," (comma) is used to separate the "name/value" pairs. Detailed reference http://www.json.org/json-zh.html
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 (user. username );
Alert (user. age );
Alert (user.info. cellphone );
Alert (user. address [0]. city );
Alert (user. address [0]. postcode );
}
This indicates that a user object has attributes such as username, age, info, and address.
You can also use JSON to modify the data.
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 (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. After downloading http://www.json.org/json.js, you can simply convert 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 objects.
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 ());
}
The following uses prototype to write a JSON ajax example.
Write a servlet (My servlet. ajax. JSONTest1.java) to write a sentence.
Java code
Response. getWriter (). print ("{\" name \ ": \" Violet \ ", \" occupation \ ": \" character \"}");
Then write an ajax request in the page.
Js Code
Function sendRequest (){
Var url = "/MyWebApp/JSONTest1 ";
Var mailAjax = newAjax. Request (
Url,
{
Method: 'get ',
OnComplete: jsonResponse
}
);
}
Function jsonResponse (originalRequest ){
Alert (originalRequest. responseText );
Var myobj = originalRequest. responseText. parseJSON ();
Alert (myobj. name );
}
The JSON method is provided in the prototype-1.5.1.js, 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 the java jar package http://www.json.org/java/index.htmlapi. The following is an example:
Add 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 = newAjax. Request (
Url,
{
Method: 'get ',
Parameters: pars,
OnComplete: jsonResponse
}
);
}
JSON request string can be used to generate and parse JSONObject, modify servlet to add JSON processing (json. jar is required)
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 (jsoneffectione ){
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 {
JSONObject jsonObj = new JSONObject (s3 );
System. out. println (jsonObj. getString ("model "));
System. out. println (jsonObj. getInt ("year "));
} Catch (jsoneffectione ){
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 (jsoneffectione ){
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 );
}

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.