UNPKG

xml-to-json-util

Version:

xml-to-json-util is a simple and efficient utility library for converting XML data to JSON format easily.

40 lines 1.49 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.xmlToJsonUtil = void 0; const lodash_1 = require("lodash"); const safeJsonParse = require("safe-json-parse/tuple"); const xmljs = require("xml-js"); const xmlToJsonUtil = (initialXml, xmlReplacementPatterns = []) => { if (!(0, lodash_1.isString)(initialXml)) { throw `First paramater 'xml' must be a string`; } const xml = processXml(xmlReplacementPatterns, initialXml); const options = { sanitize: true, ignoreDoctype: true, ignoreDeclaration: true, ignoreInstruction: true, ignoreAttributes: true, ignoreCdata: true, compact: true, ignoreComment: true, spaces: 2, }; const parsedXml = (0, lodash_1.defaultTo)((0, lodash_1.nth)(safeJsonParse(xmljs.xml2json(xml, options)), 1), {}); return flattenObjectProperties(parsedXml); }; exports.xmlToJsonUtil = xmlToJsonUtil; const processXml = (xmlReplacementPatterns, xml) => (0, lodash_1.reduce)(xmlReplacementPatterns, (acc, regex) => acc.replace(regex, ''), xml); const flattenObjectProperties = (obj) => { const propToFlatten = '_text'; (0, lodash_1.forEach)(obj, (_, key) => { if ((0, lodash_1.has)(obj[key], propToFlatten)) { obj[key] = obj[key][propToFlatten]; } else { flattenObjectProperties(obj[key]); } }); return obj; }; //# sourceMappingURL=xml.to.json.util.js.map