Skip to content

Instantly share code, notes, and snippets.

@Spencer-Easton
Created April 8, 2015 17:30
Show Gist options
  • Save Spencer-Easton/9955d97fb1a6104aeb85 to your computer and use it in GitHub Desktop.
Save Spencer-Easton/9955d97fb1a6104aeb85 to your computer and use it in GitHub Desktop.
Script to convert XML to JSON using XmlService - Originaly published in a +Google Apps Script community thread by Eric Koleda
/**
* Converts an XML string to a JSON object, using logic similar to the
* sunset method Xml.parse().
* @param {string} xml The XML to parse.
* @returns {Object} The parsed XML.
*/
function xmlToJson(xml) {
var doc = XmlService.parse(xml);
var result = {};
var root = doc.getRootElement();
result[root.getName()] = elementToJson(root);
return result;
}
/**
* Converts an XmlService element to a JSON object, using logic similar to
* the sunset method Xml.parse().
* @param {XmlService.Element} element The element to parse.
* @returns {Object} The parsed element.
*/
function elementToJson(element) {
var result = {};
// Attributes.
element.getAttributes().forEach(function(attribute) {
result[attribute.getName()] = attribute.getValue();
});
// Child elements.
element.getChildren().forEach(function(child) {
var key = child.getName();
var value = elementToJson(child);
if (result[key]) {
if (!(result[key] instanceof Array)) {
result[key] = [result[key]];
}
result[key].push(value);
} else {
result[key] = value;
}
});
// Text content.
if (element.getText()) {
result['Text'] = element.getText();
}
return result;
}
/*
* @param {Object} Array of Element objects
* @param {string} Attribute to find
* @returns {string} The Value of the Attribute
*/
function getElementValue(obj,attr){
for(var i in obj){
if(obj[i].name == attr)
return obj[i].value;
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment