Detailed explanation of XML and JSON mutual conversion function realized by JavaScript

  • 2021-07-21 07:12:57
  • OfStack

In this paper, an example is given to describe the mutual conversion function between XML and JSON realized by JavaScript. Share it for your reference, as follows:

Here, let's share an example about JavaScript realizing the mutual conversion between XML and JSON, which introduces three foreign examples of xml to json. I hope these examples can help you.

Recently, an online XML editor is being developed, and it is planned to use JSON as an intermediate format. Compared with XML, JSON has the advantages of easy reading, fast parsing speed and small space occupation, so it is easier to transfer data on WEB. However, in actual use, some details that are easy to be ignored are found. For the situation that the original structure of XML needs to be strictly guaranteed, some attention should be paid when converting to JSON.

The format for converting XML to JSON is roughly as follows:

XML form


<article>
<header id="h1">  Title of an article  </header>
<section id="s1">
<header>  Chapter title  </header>
<p>  Chapter paragraph  </p>
</section>
</article>

JSON expression


{
"article": {
"header": {
"#text": " Title of an article ",
"@id": "h1"
},
"section": {
"@id": "s1",
"header": " Chapter title ",
"p": " Chapter paragraph "
}
}
}

Using Js to convert XML into JSON scripts, I found some ready-made scripts on the Internet, but most of them only meet the relatively simple situation, and they can't complete the mutual transformation of the original structure. Here are some scripts or articles found on the Internet:

x2js : https://code.google.com/p/x2js/

jsonxml :http://davidwalsh.name/convert-xml-json

JKL.ParseXML :http://www.kawa.net/works/js/jkl/parsexml-e.html

x2js does not restore the following XML correctly.


//XML Form 
<p> <strong> Chapter </strong> Segment <em> Fall </em> </p>

The second script, jsonxml, in the case of "text mixed tags" above, does not extract the tags, but converts them into the following format.


{"p":"<strong> Chapter </strong> Segment <em> Fall </em>"}}

After that, I made some changes and parsed it into the following format, which satisfied the situation that "text mixed label" can be restored correctly.


{"p":[{"strong":" Chapter "}," Segment ",{"em":" Fall "}]}

In addition, the following code, which uses the script mentioned above for conversion, will also lead to the situation that it cannot be restored correctly.


<article>
  <section id="s1"> No. 1 1 Section </section>
  <header id="h1">  Title  </header>
  <section id="s2"> No. 1 2 Section </section>
</article>

Similarly, within a tag, its child tag appears more than once. If you need to record the path of data, you should use an array to save this structure. The correct code should be:


{
  "article": [ {
  "section": {
  "#text": " No. 1 1 Section ",
  "@id": "s1"
  },
  }, {
  "header": {
  "#text": " Title ",
  "@id": "h1"
  }
  }, {
  "section": {
  "#text": " No. 1 1 Section ",
  "@id": "s2"
  }
  }
  ]
}

jkl.parsexml


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items>
 <item>
  <zip_cd>10036</zip_cd>
  <us_state>NY</us_state>
  <us_city>New York</us_city>
  <us_dist>Broadway</us_dist>
 </item>
</items>

SAMPLE SCRIPT:


<script type="text/javascript" src="jkl-parsexml.js"></script>
<script><!--
  var url = "zip-e.xml";
  var xml = new JKL.ParseXML( url );
  var data = xml.parse();
  document.write( data["items"]["item"]["us_state"] );
  document.write( data.items.item.us_state );
// --></script>

OUTPUT JSON:


{
 items: {
  item: {
   zip_cd: "1000001"
   us_state: "NY",
   us_city: "New York",
   us_dist: "Broadway",
  }
 }
};

jsonxml


{
"article": {
"header": {
"#text": " Title of an article ",
"@id": "h1"
},
"section": {
"@id": "s1",
"header": " Chapter title ",
"p": " Chapter paragraph "
}
}
}
0

The major change I needed to implement was using attributes.item(j) instead of the attributes[j] that most of the scripts I found used. With this function, XML that looks like:


{
"article": {
"header": {
"#text": " Title of an article ",
"@id": "h1"
},
"section": {
"@id": "s1",
"header": " Chapter title ",
"p": " Chapter paragraph "
}
}
}
1

...becomes workable a JavaScript object with the following structure:


{
"article": {
"header": {
"#text": " Title of an article ",
"@id": "h1"
},
"section": {
"@id": "s1",
"header": " Chapter title ",
"p": " Chapter paragraph "
}
}
}
2

After talking for a long time, I sorted out an example below


function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof (obj[nodeName].length) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};

PS: Here are several online tools for xml and json operation for your reference:

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

Online Formatting XML/Online Compressing XML:
http://tools.ofstack.com/code/xmlformat

XML Online Compression/Formatting Tools:
http://tools.ofstack.com/code/xml_format_compress

Online JSON code verification, verification, beautification and formatting tools:
http://tools.ofstack.com/code/json

JSON Online Formatting Tool:
http://tools.ofstack.com/code/jsonformat

Online json compression/escape tool:
http://tools.ofstack.com/code/json_yasuo_trans

For more information about JavaScript, please see the topics on this site: "Summary of ajax Operation Skills in JavaScript", "Summary of JavaScript Operation Skills in XML File", "Summary of json Operation Skills in JavaScript", "Summary of JavaScript Error and Debugging Skills" and "Summary of JavaScript Data Structure and Algorithm Skills"

I hope this paper is helpful to everyone's JavaScript programming.


Related articles: