Skip to content

Instantly share code, notes, and snippets.

@chemax
Created July 13, 2018 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chemax/f658e337ab4e189c5607c2a8ae392d02 to your computer and use it in GitHub Desktop.
Save chemax/f658e337ab4e189c5607c2a8ae392d02 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const delimiter = ";";
const pathToFile = "./books.csv";
const encoding = 'utf8';
const jsonFile = pathToFile.replace('.csv', '.json');
fs.readFile(pathToFile, encoding, generateJSON);
function generateJSON(err, data) {
if (err) throw err;
let books = {authors: []};
let authors = {};
let strings = data.trim().split('\n');
let head = strings.splice(0, 1)[0].trim().replace(delimiter + ' ', delimiter).split(delimiter);
let authorsColumn = head.findIndex((el, i, arr) => {
return el.trim() === 'Author'
});
let titleColumn = head.findIndex((el, i, arr) => {
return el.trim() === 'Title'
});
let AnnotationColumn = head.findIndex((el, i, arr) => {
return el.trim() === 'Annotation'
});
for (let s in strings) {
let string = (strings[s].trim().split(delimiter));
let author = string[authorsColumn].trim();
let book = {
title: string[titleColumn].trim(),
description: string[AnnotationColumn].trim()
};
if (!authors[author]) authors[author] = [];
authors[author].push(book)
}
// console.log(authors);
for (let a in authors) {
books.authors.push({
author: a,
books: authors[a]
});
// console.log(authors[a])
}
let booksJson = JSON.stringify(books);
fs.writeFile(jsonFile, booksJson, (err) => {
if (err) throw err;
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment