Skip to content

Instantly share code, notes, and snippets.

@epappas
Created June 24, 2014 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epappas/a5514c68e181c4bc0dac to your computer and use it in GitHub Desktop.
Save epappas/a5514c68e181c4bc0dac to your computer and use it in GitHub Desktop.
Lightweight JSON to XML translator
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