83 lines
2.4 KiB
TypeScript
83 lines
2.4 KiB
TypeScript
import * as fs from 'fs';
|
|
import * as json2csv from 'json2csv';
|
|
|
|
interface FlattenData {
|
|
[key: string]: string | number | FlattenData;
|
|
}
|
|
|
|
function flattenJson(data: any, parentKey = '', separator = '.'): FlattenData {
|
|
const flattenedData: FlattenData = {};
|
|
for (const key in data) {
|
|
if (data.hasOwnProperty(key)) {
|
|
const newKey = parentKey ? `${parentKey}${separator}${key}` : key;
|
|
if (typeof data[key] === 'object' && !Array.isArray(data[key])) {
|
|
const nestedData = flattenJson(data[key], newKey, separator);
|
|
Object.assign(flattenedData, nestedData);
|
|
} else {
|
|
flattenedData[newKey] = data[key];
|
|
}
|
|
}
|
|
}
|
|
return flattenedData;
|
|
}
|
|
|
|
export function createCsvFromJson(jsonData: string, csvFilePath: string): void {
|
|
// Load JSON data
|
|
const data = JSON.parse(jsonData);
|
|
|
|
// Flatten JSON data
|
|
const flattenedData = flattenJson(data);
|
|
|
|
// Get headers from flattened data
|
|
const headers = Object.keys(flattenedData);
|
|
|
|
// Convert flattened data to array of objects for json2csv
|
|
const rows = [flattenedData];
|
|
|
|
// Create CSV file
|
|
const csv = json2csv.parse(rows, { fields: headers });
|
|
fs.writeFileSync(csvFilePath, csv);
|
|
console.log(`CSV file created at: ${csvFilePath}`);
|
|
}
|
|
|
|
export function createCsvFromJsonArray(jsonDataArray: any[], csvFilePath: string): void {
|
|
// Flatten JSON data in array
|
|
const flattenedDataArray = jsonDataArray.map((data) => flattenJson(data));
|
|
|
|
// Get headers from flattened data
|
|
const headers = Array.from(
|
|
new Set(flattenedDataArray.flatMap((data) => Object.keys(data)))
|
|
);
|
|
|
|
// Convert flattened data to array of objects for json2csv
|
|
const rows = flattenedDataArray.map((data) => headers.reduce((obj, key) => {
|
|
// @ts-ignore
|
|
obj[key] = data[key] || '';
|
|
return obj;
|
|
}, {}));
|
|
|
|
// Create CSV file
|
|
const csv = json2csv.parse(rows, { fields: headers });
|
|
fs.writeFileSync(csvFilePath, csv);
|
|
console.log(`CSV file created at: ${csvFilePath}`);
|
|
}
|
|
|
|
// Example usage
|
|
// const jsonData = `{
|
|
// "name": "John",
|
|
// "age": 30,
|
|
// "address": {
|
|
// "street": "123 Main St",
|
|
// "city": "New York",
|
|
// "state": "NY",
|
|
// "zip": "10001"
|
|
// },
|
|
// "phone": {
|
|
// "home": "123-456-7890",
|
|
// "work": "987-654-3210"
|
|
// }
|
|
// }`;
|
|
|
|
// const csvFilePath = 'output.csv';
|
|
// createCsvFromJson(jsonData, csvFilePath);
|