Created
March 2, 2018 14:16
-
-
Save phlik/b9c86812c84bf22b603a72b04410d5ad to your computer and use it in GitHub Desktop.
converting xml to json and pulling the data out of it
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
var _ = require('underscore'); | |
var x2js = require('xml2js'); | |
function traverseJson(path, node){ | |
function getElement(n, p){ | |
var t = n[p]; | |
if(_.isUndefined(t)){ | |
return n['$'][p]; | |
} | |
return _.isArray(t) ? t[0] : t; | |
} | |
var items = path.split('.'); | |
return _(items).reduce(function(entity, item){ | |
return getElement(entity, item); | |
}, node); | |
} | |
var xml = "<root><test jessie='Home cook'><sub party='crib'>aaaa</sub><food>bbbbbb</food></test></root>" | |
x2js.parseString(xml, function (err, result) { | |
console.log(traverseJson('root', result)); | |
console.log(traverseJson('root.test', result)); | |
console.log(traverseJson('root.test.sub', result)); | |
console.log(traverseJson('root.test.jessie', result)); | |
console.log(traverseJson('root.test.sub.party', result)); | |
console.log(traverseJson('root.test.sub.$', result)); | |
console.log(traverseJson('root.test.sub._', result)); | |
console.log(traverseJson('root.test.food', result)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment