Skip to content

Instantly share code, notes, and snippets.

@TenzenIga
Created April 29, 2020 02:12
Show Gist options
  • Save TenzenIga/80e4cbb95060429e8125eabc8197655e to your computer and use it in GitHub Desktop.
Save TenzenIga/80e4cbb95060429e8125eabc8197655e to your computer and use it in GitHub Desktop.
csvToJson.js
const fs = require('fs');
let reader = fs.createReadStream('books.csv', 'utf8');
let writer = fs.createWriteStream("books.json");
let result= [];
let index = null;
let data = '';
reader.on('data', (chunk) =>{
data += chunk
})
reader.on('end', ()=>{
//slpit into array of strings
data = data.split(/\r\n/);
//get rid off first row and split each item into array of [ title, author, description]
data = data.slice(1).map(i => i.split(';'))
for (let i = 0; i < data.length; i++) {
//check if author already in list
index = result.findIndex(item => item.author === data[i][1]);
//if not add author and books
if(index === -1){
result.push({
author: data[i][1],
books:[{
title: data[i][0],
description:data[i][2]
}]
})
//else add book info to existing author's books array
}else{
result[index].books.push(
{
title: data[i][0],
description:data[i][2]
})
}
}
writer.write(JSON.stringify({authors:result}))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment