thomasfrank.se

XML to JSON -- a converter

June 8, 2006

Update January 22, 2008:
Big thanks to all of you who used this script, complained about its shortcomings and asked for improvements. I never thought that it would get so much attention. Actually the use I intended for it was mainly conversion in an JavaScript environment without access to a browser DOM.
If you are running in a browser there are so many scripts out there today that do a better job. I recommend the one you can find at www.terracoder.com
There are probably tons of XML to JSON converters floating around out there by now, some written in JavaScript and some in different server side languages. Anyway I wrote this one, xml2json.js, about a year ago -- it's small (5 kB) and rather fast. You can download and use it for free. You can also try it out here:


How to use xml2json

To use xml2json you simply embed it in the head section of your web pages, before any other scripts that uses it.
<head>
<script type="text/javascript" src="xml2json.js"></script>
...
</head>


Then you use the method xml2json.parser() to convert your XML:
// A simple call - myXML is a string containing your XML:
myJsonObject=xml2json.parser(myXML);

// A 2:nd, optional, parameter is "tags not to convert" - for example <b> and <i>:
myJsonObject=xml2json.parser(myXML,'b,i');

// A 3:rd, optional, parameter gives us a string showing us the JSON structure 
// instead of the actual JSON object:
myString=xml2json.parser(myXML,'','html');

// - use "compact" for output without linebreaks or tabbing
// - use "normal" for output with linebreaks and tabbing
// - use "html" for a html representation

When to use client side conversion?

Use the converter when you can see an advantage in client side conversion. For example this converter has been a part of the studentlitteratur.se search engine for some time now.
Studentlitteratur uses a Google Mini server for the actual search. To Google Mini returns XML to the main server - which spits it out practically raw to the clients (to speed things up and reduce server load). The converter then converts the XML to JSON and another javascript parses the JSON and builds some nice old HTML that displays the search result to the user.

Are there others out there?

As always I appreciate any comments on this article. It would also be interesting if you know about other XML to JSON converters - written in JavaScript or other languages. Please post a link here if you do.
The only converter I've looked at so far written in JavaScript, except my own, is Yusuke Kawasaki's converter. He lets you decide a bit more about the end result and has tied his converter closer together with AJAX. Do have a look!
[comments]