Search This Blog

Tuesday, 7 May 2013

XML2JSON with javascript

This post is more or less a code snippet how to convert a XML-Content into JSON with javascript.

I had a problem with a very big XML-Entity and got an error
"errorcode":"steps.xml2json.ExecutionFailed"
-> this is my solution with a javascript-policy !

Here you can see it for the request flow. Change all "request"-vars to "response" and you are ready for the response flow. 

As you can see https://gist.github.com/olegp/642667 in comments section I had to modify it a little bit, because CDATA-Tags where not parsed correct - E4X has some common problems with CDATA and I was happy to found a working solution.
-> https://developer.mozilla.org/de/docs/E4X/Processing_XML_with_E4X
...For backwards compatibility, E4X defaults to ignoring comments and CDATA sections...

Tip: If you want to modify the result look at the ignore list and play around => ["type", "space", "xmlns", "html"]

// found here https://gist.github.com/olegp/642667
function E4XtoJSON(xml, ignored) {
  var r, children = xml.*, attributes = xml.@*, length = children.length();
  if(length == 0) {
    r = xml.toString();
  } else if(length == 1) {
    var text = xml.toString();
    if(text) {
      r = text;
    }
  }
  if(r == undefined) { 
    r = {};
    for each (var child in children) {
     var name = child.localName();
     var json = E4XtoJSON(child, ignored);
     var value = r[name];
     if(value) {
       if(value.length) {
         value.push(json);
       } else {
         r[name] = [value, json]
       }
     } else {
       r[name] = json;
     }
    }
  }
  if(attributes.length()) {
    var a = {}, c = 0;
    for each (var attribute in attributes) {
      var name = attribute.localName();
      if(ignored && ignored.indexOf(name) == -1) {
        a["_" + name] = attribute.toString();
        c ++;
      }
    }
    if(c) {
      if(r) a._ = r;
      return a;
    }
  }

  return r;
};

var oldcontent=request.body.asXML;
var newcontent=JSON.stringify(E4XtoJSON(oldcontent, ["type", "space", "xmlns", "html"]), null, '  ');

request.headers['Content-Type'] = 'application/json';
request.body = newcontent;

No comments:

Post a Comment