Monday, February 21, 2011

Google Apps Script XML to JSON parser (XML Shorthand)

Sometimes it makes sense to create JSON out of XML. A perfect example is when the xmlElement object in Google Apps Script fails to support nested elements (bug has been filed and is being fixed according to Google).
Google Apps Script also supports XML Shorthand aka JSON. To convert your XML to JSON, feel free to use this piece of code (thanks to @TinusOZ for some critical fixes in the code).

var kv;
function parseXMLToShortHand(xmlElement){
  var result "";
  
  var children xmlElement.getElements();
  var childrenShortHand "";
  
  if(children == "")
  {
    if(xmlElement.getText(!= "")
    {
      childrenShortHand "\""+xmlElement.getText("\"";
    }
  }else{
    for(var 0children.lengthi++)
    {
      childrenShortHand += parseXMLToShortHand(children[i]);
      if(children.length 1)
      {
        childrenShortHand += ",";
      }
    }
  }
  
  var attribs xmlElement.getAttributes();
  var attribsShortHand "";

  
  for(var 0attribs.lengthi++)
  {
    attribsShortHand += "{\"" attribs[i].getName().getLocalName("\":\"" attribs[i].getValue("\"}";
    //check if Key/Value pair object is available
    if(kv==null){
      kv=new Object();
    }
    //Set the current namespace to the Key/Value pair for reference
    kv[attribs[i].getValue()]=attribs[i].getName().getLocalName();
    if(attribs.length 1)
    {
      attribsShortHand += ",";
    }
  }
  
  //resolve namespaces from KV pair
  elementName xmlElement.getName().getLocalName();
  if(xmlElement.getName().getNamespace()!=""){
    elementName(kv[xmlElement.getName().getNamespace()])+":"+elementName;
  }
  
  if(attribsShortHand == "")
  {
    childrenShortHand "[\"" elementName "\"," childrenShortHand "]";
  }else{
    if(childrenShortHand==""){
      childrenShortHand "[\"" elementName "\","attribsShortHand +"]";
    }else{
      childrenShortHand "[\"" elementName "\","attribsShortHand "," childrenShortHand "]";
    }
  }
  return childrenShortHand;
}