Converting JSON to XML and XML to JSON
Converting JSON to XML and back again is very useful e.g. for storing and retrieving web application state to a database.
Searching the web I found a quite extensive and robust library, honourably mentioned on xml.com, by Prof. Stefan Goessner to accomplish this conversion. However the code was not in compliance with our teams javascript code standards, and so I have taken the liberty to restructure Goessner’s two seperate scripts json2xml.js and xml2json.js into one selfcontaining script file and in the process I have made sure the code validates in JSLint.
Download: (right-click and choose “Save as…”)
JsonXml.js version 0.9-p5.
JsonXml-jsmin.js version 0.9-p5 (JSMinified).
JsonXml.zip version 0.9-p5 (zip archive containing all files incl. comparison demo).
Comparison with original implementation (demo):
XmlJson_Test.htm.
XmlJson_Test_jsmin.htm.
License:
Creative Commons GNU LGPL.
Revision history:
2008-01-29, 12:00:
v0.9-p5 fixes bug in v0.9: added handling of int and float values. See why this matters.
Transforming { pos:1, neg:-1, float:3.14 } to XML and back resulted in
{ pos:”1″, neg:”-1″, float:”3.14″ }.
2008-01-28, 16:15:
v0.9-p4 fixes bug in v0.9: added handling of empty JSON strings. See why this matters.
Transforming { string:”" } to XML and back resulted in { string: null }.
2008-01-28, 15:22:
v0.9-p3 fixes bug in v0.9: added handling of empty JSON arrays. See why this matters.
Transforming { ary:[] } to XML and back resulted in { ary: null }.
2008-01-28, 13:34:
v0.9-p2 fixes bug in v0.9-p1: #text nodes were not copied correctly.
Transforming <xml>text</xml> to JSON and back resulted in <xml></xml>.
2008-01-26, 09:20:
v0.9-p1 first release of the restructured code.
Stephan Schmidt
Nice, though I don’t know why xml2json returns a String not a JS object. And with lots of String concatenation inside it doesn’t look very fast – and not usable in production websites?
Peace
-stephan
David Pollak (from Lift): “There’s no way to convert from XML to JSON because XML contains sequences not expressible in JSON” at Stephans Blog
[...] the ways in Javascript to convert XML to JSON are either slow, very basic, use XSLT, use nasty Regex or cannot create simple JSON which feels JSON [...]
Omar
Thanks Michael. I have to use ASP.NET 2.0 and do not want to download and install 173,000 KB of a tool instead of your 7 KB, for the same thing.
PD I also like Lego, and Shotokan
PD2 I’m not alone, another fan:
“this seems like the best out of what I found:”
http://www.dynamicdrive.com/forums/showthread.php?t=46469