May 08, 2021 JSON
JavaScript Object Notation is a lightweight data exchange format. I t is based on a subset of ECMAScript. J SON uses a text format that is completely language-independent, but also uses habits similar to the C language family (including C, C, C, Java, JavaScript, Perl, Python, and so on). T hese features make JSON the ideal data exchange language. E asy to read and write, but also easy for machine resolution and generation (generally used to increase network transmission rates).
JSON's rule is simple: the object is a disordered collection of 'name/value' pairs. A n object starts with a " E ach "name" is followed by a " The details are http://www.json.org/json-zh.html
To 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(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
}
This represents a user object with properties such as username, age, info, address, and so on.
JSON can also be used to simply modify the data, modify the above example, get:
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 .js json package, http://www.json.org/json.js downloaded, introduced and then simply converted into JSON data using object.to JSONString().
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());
}
Here's an ajax example of JSON using prototype.
Write a servlet first (mine is servlet.ajax.JSONTest1.java) and write a word
Java code
response.getWriter().print("{ \"name\": \"Violet\", \"occupation\": \"character\" }");
Write another 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 JSON method, String.evalJSON(), which can be modified without using .js json method
js code
function jsonResponse(originalRequest) {
alert(originalRequest.responseText);
var myobj = originalRequest.responseText.evalJSON(true);
alert(myobj.name);
}
JSON also provides java jar packages http://www.json.org/java/index.html API is simple, for example
Fill in the javascript with the request parameters
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, you can simply generate and parse JSONObject, modify the servlet to add JSON processing (to use .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 {
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);
}
Here's a look at the processing of json data in JS:
1, json data structure (objects and arrays)
json object: var obj s "name": "xiao", "age": 12;
JSON arrays: var objarray = [{"name": "xiao", "age": 12}, {"name": "xiao", "agn": 12}];
2, processing jason data, relying on files are: jQuery .js
3, Note: in the process of data transmission, json data is in the form of text, that is, string format exists;
The JS language operates on the JS object;
So the conversion between the json string and the JS object is the key;
4, data format
Json string: var json_str ''name': 'xiao', 'age': '12';
Josn object: var obj s "name": "xiao", "age": 12;
JS Object: Object s name: "xiao", age: 12
5, type conversion
Json string - JS object, how to use:
Indicate:
json_str, obj represents the data type in subheading 4 of this article;
obj = JSON.parse(json_str);
obj = jQuery.parseJSON(json_str);
Note: The incoming deformed johnson string (e.g., 'name:xiao', age:12') throws an exception;
Json string format, strict format: 'name': 'xiao', 'age': '12'
JS Objects - Json String:
json_str = JSON.
stringify(obj);
NOTE:
1, eval() is the JS native function, using the form: eval ('name': xiao', age: 12' ''''))'), is not secure, can not guarantee the type to convert to JS objects;
2, the above 3 methods, have passed the chrome browser test, the following is a screenshot of the test results;
Json Strings - JS Objects;
JS Objects - Json String: