UNPKG

jsonweaver

Version:

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

64 lines (63 loc) 2.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toCSV = exports.customCSVFieldGenerator = void 0; const defaultCSVFieldGenerator = (Json) => { const allKeys = Array.from(new Set(Json.flatMap(item => Object.keys(item)))); return allKeys.map(key => ({ label: key, value: key })); }; const customCSVFieldGenerator = (headerMapping) => { return () => { return Object.keys(headerMapping).map(key => ({ label: headerMapping[key], value: key })); }; }; exports.customCSVFieldGenerator = customCSVFieldGenerator; const flattenObject = (obj, prefix = '') => { return Object.entries(obj).reduce((acc, [key, value]) => { const newKey = prefix ? `${prefix}.${key}` : key; if (value && typeof value === 'object' && !Array.isArray(value)) { Object.assign(acc, flattenObject(value, newKey)); } else { acc[newKey] = value; } return acc; }, {}); }; const flattenJson = (Json) => { return Json.map((item) => flattenObject(item)); }; const toCSV = (Json, fieldGenerator = defaultCSVFieldGenerator) => { if (Json.length === 0) return ''; const flattenedJson = flattenJson(Json); const allObjectsEmpty = flattenedJson.every(item => Object.keys(item).length === 0); if (allObjectsEmpty) return ''; const fields = fieldGenerator(flattenedJson); const headers = fields.map(field => `"${field.label}"`).join(','); const rows = flattenedJson.map((row) => fields .map((field) => { const value = row[field.value]; if (value === null || value === undefined) { return ''; } else if (typeof value === 'string') { return `"${value.replace(/"/g, '""')}"`; } else if (typeof value === 'number') { return `${value}`; } else { return `"${String(value).replace(/"/g, '""')}"`; } }) .join(',')); return [headers, ...rows].join('\n'); }; exports.toCSV = toCSV;