Sunday, January 3, 2016

JavaScript - Converting JSON to XML

This post discusses how to convert between a JavaScript object, XML and JSON (not the same as a JavaScript object).

(Un)Surprisingly there is no native function to do this. There's various implementations of conversion like JXON or jQuery's parseXML, but no official standard. So chances are every developer will have to work with converting between these data interchange formats (and native JavaScript objects) depending on the use case or circumstances.

JavaScript Object to JSON is the most straightforward. Just use the browser's native JSON.stringify (or use a shim if you need to support older browsers). Or is it? Consider the following case:

var obj = ["lightsaber", "blaster", "vibroblade"]

All of these are Star Wars weapons. But this data structure has no idea what's inside it. It doesn't know that these are weapons, or star wars weapons.

So the conversion then, is not trivial to XML. So care must be taken when converting between a JavaScript object and JSON, to send the metadata of the JavaScript object along.

The notation I've seen most used is the $metadata attribute. It has the added advantage of $ not being a valid XML tag character, which means you won't accidently create a node with the metadata.

So instead, obj becomes this

var obj = {
     $weapon: [
        "lightsaber",
        "blaster",
        "vibroblade"
     ]
}

The following is a sample implementation of JavaScript object to JSON



And another sample implementation of JSON to XML



Hope this gives someone ideas, or helps someone