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

5 comments:

  1. When some one searches for his necessary thing, so he/she wants to be available that in detail, so that thing is maintained over here. outlook 365 login

    ReplyDelete
  2. With probably the most common term in Canada being 5 years, your amortization is going to be up for renewal before your mortgage is paid off, that's why our amortization schedule shows you the balance of your mortgage with the end of the term. canada mortgage calculator People could get a long term, which means lower monthly obligations. mortgage calculator

    ReplyDelete
  3. thanks for this amazing post keep posting fullstack java course in pune

    ReplyDelete