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;
}

3 comments:

  1. One adventure, where are the others?

    ReplyDelete
  2. I keep getting an "Authorization is required to perform that action." when I use this code in a Google Sites page.

    Any ideas as to how to fix it and/or why that would happen?

    Thanks

    ReplyDelete
    Replies
    1. /*

      Steps to application deploy:

      1) Save files
      2) Run Code.gs > doGet
      -> Autorize
      3) Run Code.gs > doGet (newly)
      -> Check for errors
      3) Create new version: File > Manage versions
      4) Public > Deploy web aplication...
      -> Use the new version
      5) Copy the link and access it

      Note: I use the interface in portuguese...

      */

      Delete