Last active
December 20, 2015 07:39
-
-
Save webercoder/6094677 to your computer and use it in GitHub Desktop.
node.js script to convert XML to JSON. Saves a file called converted.json to the input file's directory. Usage: node convert_js_to_json.js filename.xml [pretty]
This file contains hidden or 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 xml2js = require("xml2js"); | |
var fs = require("fs"); | |
var path = require("path"); | |
if (process.argv.length < 2) | |
throw new Exception("Usage: node " + process.argv[1] + " filename [pretty]"); | |
var filename = process.argv[2]; | |
var pretty = (process.argv[3] && process.argv[3] == "pretty" ? true : false); | |
var outputDirectory = path.dirname(filename) || __dirname; | |
fs.readFile(filename, function(err, data) { | |
if (err) throw err; | |
var parser = new xml2js.Parser(); | |
parser.parseString(data, function (err, result) { | |
var outputFilename = outputDirectory + "/converted.json"; | |
var jsonString = (pretty ? JSON.stringify(result, null, 2) : JSON.stringify(result)); | |
fs.writeFile(outputFilename, jsonString, function (err) { | |
if (err) throw err; | |
console.log("File has been saved as " + outputFilename); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment