Created
June 24, 2014 13:55
-
-
Save epappas/a5514c68e181c4bc0dac to your computer and use it in GitHub Desktop.
Lightweight JSON to XML translator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function json2xml(obj) { | |
var str = ''; | |
for(var key in obj) { | |
str += __json2xml(key, obj[key]); | |
} | |
return str; | |
}; | |
function __json2xml(parrent, props) { | |
if(typeof props !== 'object') { | |
if(props === undefined || props === null || props === '') return ('<' + parrent + ' />'); | |
return ('<' + parrent + ' >' + props + '</' + parrent + ' >'); | |
} | |
else { | |
if(Array.isArray(props) && props.length > 0) { | |
return props.reduce(function(xmlStr, val) { | |
xmlStr += __json2xml(parrent, val); | |
return xmlStr; | |
}, ''); | |
} | |
else { | |
var xml = { | |
parrent: parrent, | |
attr: [], | |
children: [], | |
value: null | |
}; | |
for(var key in props) { | |
if(key.match(/^\@/)) { | |
xml.attr.push(key + '=\"' + props[key] + '\"'); | |
} | |
else if(key === 'value') { | |
xml.value = props[key]; | |
} | |
else { | |
xml.children.push(__json2xml(key, props[key])); | |
} | |
} | |
return '<' + parrent + ' ' + xml.attr.join(' ') + ' >' + | |
(xml.value ? xml.value : xml.children.join(' ')) + | |
'</' + parrent + ' >'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment