Home > Web Front-end > JS Tutorial > More detailed code about javascript parsing json_json

More detailed code about javascript parsing json_json

WBOY
Release: 2016-05-16 18:39:16
Original
986 people have browsed it

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 the 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 an ajax example of JSON.

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

java code

response.getWriter().print("{ "name": "Violet", "occupation": "character" }");
Write an ajax request on the page

js code
Copy 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 not use json.js, modify the above 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 the java jar package http://www.json.org/java/index.html The API is also very simple. Here is an example

Fill in the 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" }");
}

can also be used JSONObject generates a JSON string, modify the servlet

java code
Copy the 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 is JavaScript Object Notation , 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
1 214 555 1214


1234 Main St
Springfield, TX 78080-1216

5678 Main St
Springfield, TX 78080-1316



http://seankelly.biz/

http://seankelly.tv/




使用JSON, 形式如下:
复制代码 代码如下:

{
"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/"}
]
}

如你所看到的,JSON有结构化的嵌套数据元素,这一点和XML相似。JSON也是基于文本的,XML也是如此。两者都使用Unicode。JSON和XML都很容易阅读。主观上,JSON更清晰,冗余更少。JSON WEB站点严格地描述了JSON语法,目前就是这样的。它确实是一个简单的小语言! XML确实适合标记文档,但是JSON是数据交互的理想格式。每个JSON文档描述了一个这样一个对象,该对象包含有:嵌套对象、数组、字符串、数字、布尔值或空值。

在这些地址卡例子代码中,JSON版本是更轻量级的,只占用了682字节的空间,而XML版本需要744字节空间。尽管这不是一个可观的节省。而实际的好处则来自解析过程。

XML对比JSON:地位丧失
通过使用XMLHttpRequest对象,可以从你的基于AJAX的应用程序取得XML和JSON文件。典型的,交互代码如下:
复制代码 代码如下:

var req = new XMLHttpRequest();
req.open("GET", "http://localhost/addr?cardID=32", /*async*/true);
req.onreadystatechange = myHandler;
req.send(/*no params*/null);

作为WEB服务器响应,你提供的处理器函数(myHandler函数)被多次调用,为你提供提前终止事务,更新进度条等机会。通常的,只有在web请求完成以后才起作用:那时,你就可以使用返回的数据了。

为了处理XML版本的地址卡数据,myHandler的代码如下:
复制代码 代码如下:

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

you The first thing done 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 end up as an object with a single named property Initially, this property identifies the type 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 still 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 with 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