Convert XML to JSON

...and avoid CORS / security issues

XML, JSON, Javascript

Recently I had to convert a website that had once run off a server to run locally, so that we could demo the site without the need for an internet connection. The site didn't use PHP or any server-side scripting language, so it seemed doable - the only problem was that it used data from an XML feed to create a single javascript in which all the XML data was stored. When accessed using the local file system, this was throwing a pesky access-control-allow-origin error. I figured at first that I could switch it to JSON, so I found a site that would convert XML to JSON. There are plenty of these around - here's the one I used:

http://jsontoxml.utilities-online.info/

So now I had JSON. The problem is, JSON still has cross domain issues. Looking in to the issue, people seemed to recommend I check out JSONP. Only problem is, all the examples I found to create JSONP required a server side scripting language, which was out of the question. Then I found the JSON.Stringify() function. This allows you to convert a javascript object into JSON notation. So all I did was load up the original site on a local server (using MAMP, in my case), and create a console.log function to log the compiled javascript object once the XML was parsed. So, assuming all of the XML data was stored in an object called superObject:

 console.log(JSON.Stringify(superObject)) 

Loading up chrome and viewing the javascript console, the entire object is output. You can just highlight it all, copy, and paste it into your javascript code like so:

 var superObject = //pasted code here ; 

Now you can cut out all of the code that went and fetched your XML / JSON, and just use this hardcoded data. Running the site from your local hard drive (assuming you have no other dynamic data you're trying to pull) won't be a problem.