search
HomeWeb Front-endJS Tutorialjavascript read and write json example_javascript skills

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.
Statement
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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function