Created
July 13, 2018 02:14
-
-
Save chemax/f658e337ab4e189c5607c2a8ae392d02 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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