Skip to content

Instantly share code, notes, and snippets.

@skaag
Created January 22, 2024 17:16
Show Gist options
  • Save skaag/a280376b914c9eea85526f7634d42974 to your computer and use it in GitHub Desktop.
Save skaag/a280376b914c9eea85526f7634d42974 to your computer and use it in GitHub Desktop.
Converts CSV data from a "data" field to actual records
// Define a function to convert a single CSV string to a JSON object
function csvToJson(csv) {
const lines = csv.split('\n').map(line => line.trim()).filter(line => line !== '');
// Split the lines at line breaks, trim whitespace, and remove empty lines
const headers = lines[0].split(',');
// Split the first line to get headers
return lines.slice(1).map(line => {
const data = line.split(',');
// Split the remaining lines to get the data
return headers.reduce((obj, header, index) => {
obj[header] = data[index];
// Create an object for each line using the headers
return obj;
}, {});
});
}
// Assume the CSV data is in the first item of the input
const csvData = $input.all()[0].json['data'];
// Convert the CSV data to JSON
const jsonData = csvToJson(csvData);
// Return data as n8n expects it, wrapped in an array of items
return jsonData.map(data => {
return {json: data};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment