Skip to content

Instantly share code, notes, and snippets.

@webercoder
Last active December 20, 2015 07:39
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 webercoder/6094677 to your computer and use it in GitHub Desktop.
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]
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