xml-jsonify
Version:
A liberal XML to JSON converter.
56 lines (46 loc) • 1.65 kB
JavaScript
;
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;
};
parse(content, options, function (err, data) {
if (err) {
return cb(err);
}
var key = objectKeyCount(data, 1, true);
if (key) {
data = data[key];
}
removeArrays(data);
cb(err, data);
});
};