UNPKG

jsonweaver

Version:

A simple utility to transform JSON data into CSV, XML, YAML, JSONLines and Markdown table formats.

40 lines (39 loc) 1.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toXML = void 0; const xmlbuilder_1 = require("xmlbuilder"); const toXML = (json, options = {}) => { if (typeof json !== 'object' || Array.isArray(json)) { throw new Error('Input must be a JSON object (not an array or primitive).'); } const { maxDepth = Infinity, arrayHandling = 'wrap' } = options; const buildXML = (obj, depth = 0) => { if (depth > maxDepth) { return; } if (Array.isArray(obj)) { if (arrayHandling === 'wrap') { return { item: obj.map((item) => buildXML(item, depth + 1)) }; } else if (arrayHandling === 'index') { return obj.reduce((acc, item, index) => { acc[`item${index}`] = buildXML(item, depth + 1); return acc; }, {}); } } else if (typeof obj === 'object' && obj !== null) { return Object.entries(obj).reduce((acc, [key, value]) => { acc[key] = buildXML(value, depth + 1); return acc; }, {}); } else if (obj === null || obj === undefined) { return ''; } return obj; }; const wrappedJson = { root: buildXML(json) }; return (0, xmlbuilder_1.create)(wrappedJson, { headless: true }).end({ pretty: true }); }; exports.toXML = toXML;