22 Feb 2017 - by 'Maurits van der Schee'
In order to support databases that are better at XML than JSON (Yes, I am talking about you SQL Server) I created some code that allows you to convert (lossless) from JSON to XML (and back).
JSON data:
{
"depth": false,
"model": "TRX-120",
"width": 100,
"test": [
{
"me": null
},
2.5
],
"height": null
}
XML data:
<root type="object">
<depth type="boolean">false</depth>
<model type="string">TRX-120</model>
<width type="number">100</width>
<test type="array">
<item type="object">
<me type="null"/>
</item>
<item type="number">2.5</item>
</test>
<height type="null"/>
</root>
The functions 'json2xml
' and 'xml2json
' convert from JSON to XML and back.
This is the function that generates XML from any JSON object and is described in the Microsoft .net documentation as a JSON-XML mapping:
function json2xml(json) {
var a = JSON.parse(json)
var c = document.createElement("root");
var t = function (v) {
return {}.toString.call(v).split(' ')[1].slice(0, -1).toLowerCase();
};
var f = function (f, c, a, s) {
c.setAttribute("type", t(a));
if (t(a) != "array" && t(a) != "object") {
if (t(a) != "null") {
c.appendChild(document.createTextNode(a));
}
} else {
for (var k in a) {
var v = a[k];
if (k == "__type" && t(a) == "object") {
c.setAttribute("__type", v);
} else {
if (t(v) == "object") {
var ch = c.appendChild(document.createElementNS(null, s ? "item" : k));
f(f, ch, v);
} else if (t(v) == "array") {
var ch = c.appendChild(document.createElementNS(null, s ? "item" : k));
f(f, ch, v, true);
} else {
var va = document.createElementNS(null, s ? "item" : k);
if (t(v) != "null") {
va.appendChild(document.createTextNode(v));
}
var ch = c.appendChild(va);
ch.setAttribute("type", t(v));
}
}
}
}
};
f(f, c, a, t(a) == "array");
return c.outerHTML;
}
I wrote also the reverse function and did the same implementation in PHP, see:
To ensure quality, I covered all code with unit tests, both in JavaScript (using QUnit) as in PHP (using PHPUnit). Enjoy!
PS: Liked this article? Please share it on Facebook, Twitter or LinkedIn.