Home Web Front-end JS Tutorial How to convert XML and JSON between JS

How to convert XML and JSON between JS

Apr 25, 2018 am 09:40 AM
javascript json Convert

This time I will bring you the method of converting XML and JSON with JS. What are the precautions for converting XML and JSON with JS? The following is a practical case, let's take a look.

During development, sometimes XML and JSON are converted to each other, and they are required to be used in JS. I searched a lot on the Internet, but every useful one either lacks arms or legs, or the words do not express the meaning, which is too useless. God's sake, I decided to realize it myself.

Comparison of the differences between JSON and XML

1. Definition introduction

(1).XML definition

Extensible Markup Language (XML) is 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 well suited 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 with good reliability Reading and fast writing features. Data exchange between different platforms is possible. JSON adopts a highly compatible and completely language-independent text format, and also has 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>. Advantages of XML

A. The format is unified and conforms to standards;
B. It is easy to interact with other systems remotely and data sharing is 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, As a result, the server-side and client-side codes become extremely complex and difficult to maintain;
C. The way of parsing XML between different client browsers is inconsistent, and a lot of code needs to be written repeatedly;
D. Server-side and client-side parsing XML consumes more 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 format They are all compressed and occupy little bandwidth;

 B. Easy to parse, client-side JavaScript can simply read JSON data through eval();

 C.Support multiple languages, Including ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and other server-side languages ​​to facilitate server-side parsing;

 D. In the PHP world, there are already PHP-JSON and JSON- PHP has appeared, and it is preferred to directly call programs serialized by PHP. PHP server-side objects, arrays, etc. can directly generate JSON format, which is convenient for client access and extraction;

 E. Because JSON format can be directly used by the server The use of code greatly simplifies the amount of code development on the server side and the client side, and the tasks remain unchanged and is easy to maintain.

<2>. Disadvantages of JSON

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

B.JSON The promotion of the format in Web Services is still in its infancy.

Convert XML and JSON to each other in Javascript

Let’s look at the calling example first:

<viewport id="menuPane" layout="border">
    <panel region="center" border="0" layout="border">
        <tbar>
            <toolbar text="XXXX">
                <menu>
                    <text text="11">
                    </text>
                    <text text="22">
                    </text>
                    <text text="33">
                    </text>
                </menu>
            </toolbar>
            <toolbar text="XXXX">
                <menu>
                    <text text="44">
                    </text>
                    <text text="55">
                    </text>
                    <menu>
                        <text text="6 6">
                        </text>
                    </menu>
                    <text text="77">
                    </text>
                </menu>
            </toolbar>
        </tbar>
    </panel>
</viewport>
var xmlParser = new XmlToJson();
var json = xmlParser.parse(xml);
console.log( JSON.stringify(json) );
var jsonParser = new JsonToXml();
var xml = jsonParser.parse(json);
console.log( xml );
Copy after login

Convert XML to JSON:

function XmlToJson() {
}
XmlToJson.prototype.setXml = function(xml) {
    if(xml && typeof xml == "string") {
        this.xml = document.createElement("p");
        this.xml.innerHTML = xml;
        this.xml = this.xml.
getElementsByTagName
("*")[0];
    }
    else if(typeof xml == "object"){
        this.xml = xml;
    }
};
XmlToJson.prototype.getXml = function() {
    return this.xml;
};
XmlToJson.prototype.parse = function(xml) {
    this.setXml(xml);
    return this.convert(this.xml);
};
XmlToJson.prototype.convert = function(xml) {
    if (xml.nodeType != 1) {
        return null;
    }
    var obj = {};
    obj.xtype = xml.nodeName.toLowerCase();
    var nodeValue = (xml.textContent || "").replace(/(\r|\n)/g, "").replace(/^\s+|\s+$/g, "");
    
    if(nodeValue && xml.childNodes.length == 1) {
        obj.text = nodeValue;
    }
    if (xml.attributes.length > 0) {
        for (var j = 0; j < xml.attributes.length; j++) {
            var attribute = xml.attributes.item(j);
            obj[attribute.nodeName] = attribute.nodeValue;
        }
    }
    if (xml.childNodes.length > 0) {
        var items = [];
        for(var i = 0; i < xml.childNodes.length; i++) {
            var node = xml.childNodes.item(i);
            var item = this.convert(node);
            if(item) {
                items.push(item);
            }
        }
        if(items.length > 0) {
            obj.items = items;
        }
    }
    return obj;
};
Copy after login

Convert JSON to XML:

function JsonToXml() {
 this.result = [];
}
JsonToXml.prototype.spacialChars = ["&","<",">","\"","&#39;"];
JsonToXml.prototype.validChars = ["&","<",">",""","&#39;"];
JsonToXml.prototype.toString = function(){
 return this.result.join("");
};
JsonToXml.prototype.replaceSpecialChar = function(s){
    for(var i=0;i<this.spacialChars.length;i++){
        s=s.replace(new RegExp(this.spacialChars[i],"g"),this.validChars[i]);
    }
    return s;
};
JsonToXml.prototype.appendText = function(s){
    s = this.replaceSpecialChar(s);
    this.result.push(s);
};
JsonToXml.prototype.appendAttr = function(key, value){
    this.result.push(" "+ key +"=\""+ value +"\"");
};
JsonToXml.prototype.appendFlagBeginS = function(s){
 this.result.push("<"+s);
};
JsonToXml.prototype.appendFlagBeginE = function(){
 this.result.push(">");
};
JsonToXml.prototype.appendFlagEnd = function(s){
 this.result.push("</"+s+">");
};
JsonToXml.prototype.parse = function(json){
 this.convert(json);
 return this.toString();
};
JsonToXml.prototype.convert = function(obj) {
 var nodeName = obj.xtype || "item";
 this.appendFlagBeginS(nodeName);
 var arrayMap = {};
 for(var key in obj) {
  var item = obj[key];
  if(key == "xtype") {
   continue;
  }
  if(item.constructor == String) {
   this.appendAttr(key, item);
  }
  if(item.constructor == Array) {
   arrayMap[key] = item;
  }
 }
 this.appendFlagBeginE();
 for(var key in arrayMap) {
  var items = arrayMap[key];
  for(var i=0;i<items.length;i++) {
   this.convert(items[i]);
  }
 }
 this.appendFlagEnd(nodeName);
};
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

What are the methods for parsing Json

What are the methods for JS to judge json

Detailed explanation of JSONP principles and case analysis

The above is the detailed content of How to convert XML and JSON between JS. For more information, please follow other related articles on the PHP Chinese website!

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)

Practical tips for converting full-width English letters into half-width form Practical tips for converting full-width English letters into half-width form Mar 26, 2024 am 09:54 AM

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

Detailed explanation of the implementation method of converting PHP months to English months Detailed explanation of the implementation method of converting PHP months to English months Mar 21, 2024 pm 06:45 PM

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

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.

How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone Mar 21, 2024 pm 01:21 PM

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]

How to convert full-width English letters into half-width letters How to convert full-width English letters into half-width letters Mar 25, 2024 pm 02:45 PM

How to convert full-width English letters into half-width letters In daily life and work, sometimes we encounter situations where we need to convert full-width English letters into half-width letters, such as when entering computer passwords, editing documents, or designing layouts. Full-width English letters and numbers refer to characters with the same width as Chinese characters, while half-width English letters refer to characters with a narrower width. In actual operation, we need to master some simple methods to convert full-width English letters into half-width letters so that we can process text and numbers more conveniently. 1. Full-width English letters and half-width English letters

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

PHP Tutorial: How to convert int type to string PHP Tutorial: How to convert int type to string Mar 27, 2024 pm 06:03 PM

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code

Quickly learn about ASCII value conversion in PHP Quickly learn about ASCII value conversion in PHP Mar 28, 2024 pm 06:42 PM

ASCII value conversion in PHP is a problem often encountered in programming. ASCII (American Standard Code for Information Interchange) is a standard encoding system for converting characters into numbers. In PHP, we often need to convert between characters and numbers through ASCII code. This article will introduce how to convert ASCII values ​​in PHP and give specific code examples. 1. Change the characters

See all articles