UNPKG

xml-jsonify

Version:
74 lines (59 loc) 2.01 kB
"use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var parse = require("xml2js").parseString, objectKeyCount = require("obj-key-count"), iterateObj = require("iterate-object"); /** * xmlJsonify * Converts the XML input into an object. * * @name xmlJsonify * @function * @param {String} content The XML content. * @param {Object} options The options passed to `xml2js`. * @param {Function} cb The callback function. */ module.exports = function xmlJsonify(content, options, cb) { if (typeof options === "function") { cb = options; options = {}; } var removeArrays = function removeArrays(input) { if ((typeof input === "undefined" ? "undefined" : _typeof(input)) !== "object") { return input; } if (Array.isArray(input) && input.length === 1) { return removeArrays(input[0]); } iterateObj(input, function (val, key) { if ((typeof val === "undefined" ? "undefined" : _typeof(val)) === "object" && val) { input[key] = removeArrays(val); } }); return input; }; return new Promise(function (resolve, reject) { parse(content, options, function (err, data) { if (err) { if (cb) { cb(err); } reject(err); return; } var key = objectKeyCount(data, 1, true); if (key) { data = data[key]; } removeArrays(data); if (cb) { cb(err, data); } if (err) { reject(err); } else { resolve(data); } }); }); };