sussy-util
Version:
Util package made by me
67 lines (66 loc) • 2.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class DataConverter {
/**
* It takes a CSV string and returns an array of objects.
* The first line of the CSV is assumed to be the header row.
* The header row is used to create the keys for the objects in the array.
* The values for the keys are taken from the subsequent rows.
* @param {string} csv - string - The CSV string you want to convert to JSON
* @param {string} [del=,] - The delimiter in use in the CSV file.
* @returns An array of objects.
*/
static csvToJson(csv, del = ',') {
const lines = csv.split('\n');
const headers = lines[0].split(del);
const jsonData = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(del);
const obj = {};
for (let j = 0; j < headers.length; j++) {
const header = headers[j];
let value = values[j];
if (value.startsWith('{') || value.startsWith('[')) {
value = JSON.parse(value);
}
if (!isNaN(Number(value))) {
value = Number(value);
}
if (value === 'true' || value === 'false') {
value = value === 'true';
}
obj[header] = value;
}
jsonData.push(obj);
}
return jsonData;
}
/**
* It takes an array of objects and returns a CSV string.
* The first object in the array is taken as for the properties of the csv string.
*
* The function takes two parameters:
* json: an array of objects
* del: the delimiter to use in the CSV string (defaults to a comma)
* @param {object[]} json - object[] - The JSON object you want to convert to CSV.
* @param {string} [del=,] - The delimiter to use in the CSV file.
* @returns A string
*/
static jsonToCsv(json, del = ',') {
const csvRows = [];
const headers = Object.keys(json[0]);
csvRows.push(headers.join(del));
for (const obj of json) {
const values = headers.map((header) => {
const value = obj[header];
if (typeof value === 'object') {
return JSON.stringify(value);
}
return String(value);
});
csvRows.push(values.join(del));
}
return csvRows.join('\n');
}
}
exports.default = DataConverter;