2008.01.26

Converting JSON to XML and XML to JSON

Kategori: JSON, Programmering — Michael Schøler, Kl. 09:20:04

JSONConverting 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.

2 kommentarer »

  1. 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

    Kommentar skrevet af Stephan Schmidt
    D. 10/10-2008 Kl. 08:42:03
  2. [...] 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 [...]

    Pingback skrevet af 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
    D. 10/10-2008 Kl. 09:38:18

RSS feed for kommentarer til dette indlæg. TrackBack URI

Send kommentar

*
For at bevise at du er en person, og ikke en spam-robot, skal du indtaste dette kodeord. Bemærk at kodeordet altid starter eller slutter med et tal. Klik på billedet for at få kodeordet læst op.
Click to hear an audio file of the anti-spam word