Home Web Front-end JS Tutorial Differences between JSON and XML and case applications

Differences between JSON and XML and case applications

Dec 07, 2016 am 10:29 AM
json

1. Definition introduction

(1).XML definition

Extensible Markup Language (XML), a markup language used to mark electronic documents to make them structural. It can be used to mark data and define data types. It is a source language that allows users to define their own markup language. XML uses DTD (document type definition) document type definition to organize data; the format is unified, cross-platform and language, and has long become a recognized standard in the industry.

XML is a subset of Standard Generalized Markup Language (SGML) and is very suitable for web transmission. XML provides a unified method for describing and exchanging structured data independent of applications or vendors.

(2).JSON definition

JSON (JavaScript Object Notation) is a lightweight data exchange format that has good readability and is easy to write quickly. Data exchange between different platforms is possible. JSON adopts a highly compatible and completely language-independent text format, and also has system behavior similar to C language habits (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data exchange language.

JSON is based on JavaScript Programming Language, a subset of Standard ECMA-262 3rd Edition - December 1999.

2. Advantages and disadvantages of XML and JSON

(1). Advantages and disadvantages of XML

<1>. Interaction and data sharing are more convenient.


<2> Disadvantages of XML

A. XML files are huge, the file format is complex, and transmission takes up bandwidth;

B. Both the server and the client need to spend a lot of code to parse XML, resulting in server-side and The client code becomes extremely complex and difficult to maintain;


C. The way of parsing XML between different browsers on the client is inconsistent, and a lot of code needs to be written repeatedly;


D. It costs more to parse XML on the server and client resources and time.

(2). Advantages and disadvantages of JSON

<1>. Advantages of JSON:

  A. The data format is relatively simple, easy to read and write, the formats are compressed, and it takes up little bandwidth;

  B. Easy Parsing, client-side JavaScript can simply read JSON data through eval(); C. Supports multiple languages, including ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby, etc. Server-side language facilitates server-side parsing;


  D. In the PHP world, PHP-JSON and JSON-PHP have already appeared. It is preferred that the program after PHP serialization is directly called. PHP server-side objects, arrays, etc. can be directly called Generate JSON format to facilitate client access and extraction;


E. Because the JSON format can be directly used by server-side code, it greatly simplifies the amount of code development on the server side and client side, and the task remains unchanged and is easy to maintain.


<2>. Disadvantages of JSON

A. It is not as popular and widely used as the XML format, and it is not as versatile as XML;

B. The JSON format is currently still in its infancy when promoted in Web Services stage.

3. Comparison of the advantages and disadvantages of XML and JSON

(1). In terms of readability.


The data readability of JSON and XML is basically the same. The readability of JSON and XML is almost the same. On one side is the recommended syntax and on the other side is the standardized tag form. XML is more readable.

(2). Scalability.

XML is naturally very scalable, and of course JSON has it. There is nothing that XML can expand that JSON cannot.

(3). Coding difficulty.

XML has a wealth of encoding tools, such as Dom4j, JDom, etc., and JSON also has tools provided by json.org. However, JSON encoding is obviously much easier than XML. JSON code can be written even without the help of tools, but it must be written well. XML is not so easy.

(4). Decoding difficulty.

The parsing of XML has to consider the child nodes and parent nodes, which makes people dizzy, while the difficulty of parsing JSON is almost 0. XML loses really nothing at this point.

(5). Popularity.

XML has been widely used in the industry, while JSON has just begun. However, in the specific field of Ajax, the future development must be that XML gives way to JSON. By then Ajax should become Ajaj (Asynchronous Javascript and JSON).

(6). Analysis methods.


JSON and XML also have rich parsing methods.

(7). Data volume.

Compared with XML, JSON has smaller data size and faster transmission speed.

(8). Data interaction.

The interaction between JSON and JavaScript is more convenient, easier to parse and process, and provides better data interaction.

(9). Data description.

JSON is less descriptive of data than XML.

(10). Transmission speed.

JSON is much faster than XML.

4. Comparison of XML and JSON data formats

(1). About lightweight and heavyweight

Lightweight and heavyweight are relative terms, so what is the heavyweight of XML compared to JSON? It should be reflected in parsing. XML is currently designed with two parsing methods: DOM and SAX.

<1>.DOM

DOM regards a data exchange format XML as a DOM object. The entire XML file needs to be read into the memory. The principles of JSON and XML are the same in this regard, but XML must consider parent nodes and child nodes. In this regard, JSON Parsing is much easier because JSON is built on two structures: key/value, a collection of key-value pairs; an ordered collection of values, which can be understood as an array;

<2>.SAX

SAX does not require the entire read The parsed content can be processed by entering the document, which is a step-by-step parsing method. The program can also terminate parsing at any time. In this way, a large document can be displayed gradually and bit by bit, so SAX is suitable for large-scale parsing. This is currently not possible with JSON.

So, the light/heavyweight difference between JSON and XML is:

JSON only provides an overall parsing solution, and this method can only achieve good results when parsing less data;

XML provides A stepwise analysis scheme for large-scale data, which is very suitable for processing large amounts of data.

(2). Regarding the difficulty of data format encoding and parsing

<1>. In terms of encoding.

Although XML and JSON have their own encoding tools, JSON encoding is simpler than XML. You can write JSON code even without the help of tools, but it is a bit difficult to write good XML code; just like XML, JSON is also text-based, uses Unicode encoding, and is as readable as the data exchange format XML.

Subjectively, JSON is clearer and less redundant. The JSON website provides a strict, if brief, description of JSON syntax. Generally speaking, XML is more suitable for marking documents, while JSON is more suitable for data exchange processing.

<2>. In terms of analysis.

In the field of ordinary web applications, developers often struggle with XML parsing. Whether it is generating or processing XML on the server side, or parsing XML on the client side using JavaScript, it often results in complex code and extremely low development efficiency.
In fact, for most web applications, they do not need complex XML to transmit data at all. The scalability claimed by XML rarely has an advantage here. Many Ajax applications even directly return HTML fragments to build dynamic web pages. Compared with returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but it also lacks a certain degree of flexibility. The data exchange format JSON provides greater simplicity and flexibility than XML or HTML fragments. In Web Service applications, at least for now, XML still has an unshakable position.

(3). Example comparison

Both XML and JSON use structured methods to mark data. Let’s make a simple comparison below.

<1>. Use XML to represent the data of some provinces and cities in China as follows:

   
<?xml version="1.0" encoding="utf-8" ?>
<country>
<name>中国</name>
<province>
<name>黑龙江</name>
<citys>
<city>哈尔滨</city>
<city>大庆</city>
</citys>   
</province>
<province>
<name>广东</name>
<citys>
<city>广州</city>
<city>深圳</city>
<city>珠海</city>
</citys>   
</province>
<province>
<name>台湾</name>
<citys>
 <city>台北</city>
 <city>高雄</city>
</citys> 
</province>
<province>
<name>新疆</name>
<citys>
<city>乌鲁木齐</city>
</citys>
</province>
</country>
Copy after login

<2>. Use JSON to represent the data of some provinces and cities in China as follows

var country =
{
name: "中国",
provinces: [
{ name: "黑龙江", citys: { city: ["哈尔滨", "大庆"]} },
{ name: "广东", citys: { city: ["广州", "深圳", "珠海"]} },
{ name: "台湾", citys: { city: ["台北", "高雄"]} },
{ name: "新疆", citys: { city: ["乌鲁木齐"]} }
]
}
Copy after login

The readability of encoding In terms of XML, it has obvious advantages. After all, human language is closer to such a description structure. JSON reads more like a data block and is more confusing to read. However, the language that is difficult for us to read is suitable for machine reading, so the value "Heilongjiang" can be read through the JSON index country.provinces[0].name.

In terms of the handwriting difficulty of coding, XML is more comfortable. It is easy to read and of course easy to write. However, the written JSON characters are obviously much less. If you remove the blank tabs and line breaks, JSON is densely packed with useful data, while XML contains many repeated markup characters.

Case application: Provincial three-level linkage

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/封装Ajax.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<select name="provence" id="provence" onchange="chooseP(this.value)">
<option>湖北省</option>
</select>
<select name="city" id="city" onchange="chooseC(this.value)">
<option>武汉市</option>
</select>
<select name="area" id="area">
<option>江城区</option>
</select>
</body>
<script>
objAJAX.getAjax("get", "xml/Provinces.xml", "", callBackOk, callBackFail, "");
function callBackOk(data) {
var provences = data.getElementsByTagName("Province");
/*<Province ID="1" ProvinceName="北京市">北京市</Province> */
for(var i = 0; i < provences.length; i++) {
var Potion = document.createElement("option"); //<option><option/>
Potion.value = provences[i].getAttribute("ID"); //把id传给value
Potion.innerHTML = provences[i].innerHTML;
document.getElementById("provence").appendChild(Potion);
}
}
function callBackFail() {
alert("服务器出错啦")
}
//市级联动
function chooseP(id) {
objAJAX.getAjax("get", "xml/Cities.xml", "", callBackOkP, callBackFailP, "");
function callBackOkP(data) {
document.getElementById("city").innerHTML = "";
//alert( typeof data)
var citys = data.getElementsByTagName("City");
//alert(citys.length)
/*<City ID="1" CityName="北京市" PID="1" ZipCode="100000">北京市</City>*/
for(var i = 0; i < citys.length; i++){
var Coption = document.createElement("option"); //<option><option/>
Coption.value = citys[i].getAttribute("ID");
var PID = citys[i].getAttribute("PID");
if(id == PID) {
Coption.innerHTML = citys[i].innerHTML;
var dd=Coption.value;
document.getElementById("city").appendChild(Coption);
}
}
alert(Cvalue);
chooseC(Cvalue);
}
function callBackFailP() {
alert("服务器出错啦")
}
}
//县级联动
function chooseC(id) {
objAJAX.getAjax("get", "xml/Districts.xml", "", callBackOkP, callBackFailP, "");
function callBackOkP(data) {
document.getElementById("area").innerHTML = "";
//alert( typeof data)
var districts = data.getElementsByTagName("District");
//alert(citys.length)
/* <District ID="1" DistrictName="东城区" CID="1">东城区</District>*/
for(var i = 0; i < districts.length; i++) {
var Xoption = document.createElement("option"); //<option><option/>
Xoption.value = districts[i].getAttribute("ID");
var CID = districts[i].getAttribute("CID");
if(id == CID) {
Xoption.innerHTML = districts[i].innerHTML;
document.getElementById("area").appendChild(Xoption);
}
}
}
function callBackFailP() {
alert("服务器出错啦")
}
}
</script>
</html>
Copy after login


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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

How to exclude a field from JSON using @Expose annotation in Java? How to exclude a field from JSON using @Expose annotation in Java? Sep 16, 2023 pm 09:49 PM

The Gson@Expose annotation can be used to mark whether a field is exposed (contained or not) for serialization or deserialization. The @Expose annotation can take two parameters, each parameter is a boolean value and can take the value true or false. In order for GSON to react to the @Expose annotation, we have to create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, which configures Gson to exclude all fields without Expose annotation from serialization or deserialization. Syntax publicGsonBuilderexclud

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

See all articles