Home > Web Front-end > JS Tutorial > javascript read and write json example_javascript skills

javascript read and write json example_javascript skills

WBOY
Release: 2016-05-16 16:52:43
Original
1472 people have browsed it

JSON (JavaScript Object Notation) is a simple data format that is more lightweight than xml. JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.

The rules of JSON are simple: an object is an unordered collection of "name/value" pairs. An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by a "," (comma). For specific details, please refer to http://www.json.org/json-zh.html

A simple example:

js code

Copy code The code is 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 with attributes such as username, age, info, address, etc.

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

js code
Copy code The code is 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 json.js package, download http ://www.json.org/json.js After importing it, you can simply use object.toJSONString() to convert it into JSON data.

js code
Copy code The code is 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 The code is as follows:

function myEval() {

var str = '{ "name": "Violet", "occupation": "character" }';

var obj = eval('(' str ')');

alert(obj.toJSONString());

}

or use parseJSON() method

js code
Copy code The code is as follows:

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.

First write a servlet (mine is servlet.ajax.JSONTest1.java) and write a sentence

java code
Copy Code The code is as follows:

response.getWriter().print("{ /"name/": /"Violet/", /"occupation/": /"character/" }");

Write an ajax request in the page

js code
Copy the code The code is 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 JSON method, String.evalJSON(), you can modify the above without using json.js Method

js code
Copy code The code is as follows:

function jsonResponse( originalRequest) {

alert(originalRequest.responseText);

var myobj = originalRequest.responseText.evalJSON(true);

alert(myobj.name);

}

JSON also provides java jar package http://www.json.org/java/index.html The API is also very simple, here is an example

Add request parameters in javascript

js code
Copy code The code is 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, you can simply generate JSONObject and parse it, modify the servlet to add JSON processing (you need to use json.jar)

java Code
Copy code The code is 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 a JSON string and modify the servlet

java code
Copy code The code is 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 The code is 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

Use JSON
JSON also It is JavaScript Object Notation, which is a lightweight syntax for describing data. JSON is elegant because it is a subset of the JavaScript language. Next you'll see why this is so important. First, let's compare JSON and XML syntax.

Both JSON and XML use structured methods to describe data. For example, an address book application can provide a web service for generating address cards in XML format:
Copy code The code is as follows:



Sean Kelly
SK Consulting

kelly@seankelly.biz

kelly@seankelly.tv



1 214 555 1212
1 214 555 1213 🎜>


1234 Main St
Springfield, TX 78080-1216

5678 Main St
Springfield, TX 78080-1316



http://seankelly.biz/

http://seankelly.tv/





Use JSON, the form is 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, similar to XML. JSON is also text-based, as is XML. Both use Unicode. Both JSON and XML are easy to read. Subjectively, JSON is cleaner and less redundant. The JSON WEB site strictly describes JSON syntax, and that's how it is currently. It really is a simple little language! XML is indeed suitable for marking up 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 more lightweight, taking up only 682 bytes of space, while the XML version requires 744 bytes of space. Although this is not a substantial saving. The actual benefit comes from the parsing process.

XML vs. JSON: Loss of Status
XML and JSON files can be obtained from your AJAX-based application by using the XMLHttpRequest object. Typically, the interaction code is 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 the WEB server responds, the handler function (myHandler function) you provided is called multiple times, providing you with opportunities to terminate the transaction early, update the progress bar, etc. Normally, this only works after the web request has completed: at that point, you can use the returned data.

In order to process the XML version of the address card data, the code of myHandler is as follows:
Copy the code The code is as follows:

function myHandler() {
if (req.readyState == 4 /*complete*/) {
// Update address field in a form with first street 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's worth noting that you don't have to parse the XML document: the XMLHttpRequest object is parsed automatically and makes the DOM tree available in responseXML. By using the responseXML attribute, you can call the getElementsByTagName method to find the address part of the document. You can also use the first one to find it. Then, you can call getElementsByTagName again to find the first address element in the address part. 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, the results can be displayed in a form field.

It is indeed not a simple job, now, try again using JSON:
Copy the code The code is 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 calling the eval function. Parsing JSON only takes one line! Additionally, manipulating objects in JSON is just like manipulating other JavaScript objects. This is obviously simpler than manipulating through the 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 the home address object
card.fullname is the name of the card, "Sean Kelly"
If you look more closely, you may find that the document in XML format is at least There is a follower element, card. This doesn't exist in JSON, why? Presumably, if you're developing JavaScript to access a web service, you already know what you want. However, you can use this in JSON:
{"card": {"fullname": ...}}

Using this technique, your JSON file will always start with a single name The object starts with a property that identifies the kind of object.

Is JSON fast and reliable?

JSON provides lightweight small documents, and JSON is easier to use in JavaScript. XMLHttpRequest automatically parses the XML document for you, and you have to parse the JSON file manually. But is parsing JSON slower than parsing XML? The author has used XMLHttpRequest to parse XML and parse JSON through thousands of repeated tests. The result is that parsing JSON is 10 times faster than XML! When looking at AJAX as a desktop application, where speed is the most important factor, it's clear that JSON is superior.

Of course, you can't always control the server side to generate data for an AJAX program. You can also use a third-party server to provide XML-formatted output instead of the server. And, if the server happens to serve JSON, are you sure you actually want to use it?

What's worth noting in your code is that you're passing the response text directly into eval. You can do this if you control the server. If not, a malicious server can cause your browser to perform dangerous actions. In cases like this, you're better off using code written in JavaScript to parse the JSON. Fortunately, this already exists.

Speaking of parsing, Python enthusiasts may notice that JSON is not just a subset of JavaScript, it is also a subset of Python. You can execute JSON directly in Python, or use secure JSON parsing instead. The JSON.org website lists many commonly used JSON parsers.

Server-Side JSON

By now, you may have focused on the use of JSON in AJAX-based web applications running in client browsers. Naturally, first, the data in JSON format must be generated on the server side. Fortunately, creating JSON or converting other existing data to JSON is fairly simple. Some WEB application frameworks, such as TurboGears, automatically include support for JSON output.

In addition, commercial WEB service providers have also taken notice of JSON. Yahoo has recently created many JSON-based web services. Yahoo's various search services, fulfillment plans, del.icio.us, and highway traffic services also support JSON output. No doubt other major web service providers will also add support for JSON.

Summary

The cleverness of JSON is that it is a subset of JavaScript and Python, making it easier to use and providing efficient data interaction for AJAX. It parses faster and is easier to use than XML. JSON is becoming the strongest voice of "Web 2.0" now. Every developer, whether it's a standard desktop application or a web application, is increasingly noticing its simplicity and convenience. I hope you can experience the joy of applying JSON in buzzword-compliant, Web-2.0-based, AJAX-enabled, agile development.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template