Skip to content

Instantly share code, notes, and snippets.

@Max-Makhrov
Created March 13, 2020 15:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Max-Makhrov/3179ef3b0b2717c0edcd10f8baed3595 to your computer and use it in GitHub Desktop.
Save Max-Makhrov/3179ef3b0b2717c0edcd10f8baed3595 to your computer and use it in GitHub Desktop.
Google Apps Script to convert XML to JSON
function test_xmlToJson(xmlString) {
var xmltext = '<ALEXA VER="0.9" URL="davidwalsh.name/" HOME="0" AID="="><SD TITLE="A" FLAGS="" HOST="davidwalsh.name"><TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/><LINKSIN NUM="1102"/><SPEED TEXT="1421" PCT="51"/></SD><SD><POPULARITY URL="davidwalsh.name/" TEXT="7131"/><REACH RANK="5952"/><RANK DELTA="-1648"/></SD></ALEXA>';
var xml = XmlService.parse(xmltext);
Logger.log(JSON.stringify(xmlToJson_(xml)));
// returns this:
//{
// "ALEXA":{
// "@attributes":{
// "VER":"0.9",
// "URL":"davidwalsh.name/",
// "HOME":"0",
// "AID":"="
// },
// "SD":[
// {
// "@attributes":{
// "TITLE":"A",
// "FLAGS":"",
// "HOST":"davidwalsh.name"
// },
// "TITLE":{
// "@attributes":{
// "TEXT":"David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"
// }
// },
// "LINKSIN":{
// "@attributes":{
// "NUM":"1102"
// }
// },
// "SPEED":{
// "@attributes":{
// "TEXT":"1421",
// "PCT":"51"
// }
// }
// },
// {
// "POPULARITY":{
// "@attributes":{
// "URL":"davidwalsh.name/",
// "TEXT":"7131"
// }
// },
// "REACH":{
// "@attributes":{
// "RANK":"5952"
// }
// },
// "RANK":{
// "@attributes":{
// "DELTA":"-1648"
// }
// }
// }
// ]
// }
//}
}
// Changes XML to JSON
// Original code: https://davidwalsh.name/convert-xml-json
function xmlToJson_(xml) {
// Create the return object
var obj = {};
// get type
var type = '';
try { type = xml.getType(); } catch(e){}
if (type == 'ELEMENT') {
// do attributes
var attributes = xml.getAttributes();
if (attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < attributes.length; j++) {
var attribute = attributes[j];
obj["@attributes"][attribute.getName()] = attribute.getValue();
}
}
} else if (type == 'TEXT') {
obj = xml.getValue();
}
// get children
var elements = [];
try { elements = xml.getAllContent(); } catch(e){}
// do children
if (elements.length > 0) {
for(var i = 0; i < elements.length; i++) {
var item = elements[i];
var nodeName = false;
try { nodeName = item.getName(); } catch(e){}
if (nodeName)
{
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson_(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson_(item));
}
}
}
}
return obj;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment