Skip to content

Instantly share code, notes, and snippets.

@HerbertLim
Created September 22, 2019 05:54
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 HerbertLim/25f0ffb31162dbf0e97e602ba2d01379 to your computer and use it in GitHub Desktop.
Save HerbertLim/25f0ffb31162dbf0e97e602ba2d01379 to your computer and use it in GitHub Desktop.
Simple example of converting CSV to JSON object
import parse from 'csv-parse/lib/sync';
import fs from 'fs'
const csv = fs.readFileSync('src/countries.csv')
const records = parse(csv.toString('utf-8'), {
columns: true,
skip_empty_lines: true
})
fs.writeFileSync('src/countrycode.js', JSON.stringify(records, null, 2))
/* csv file contains following lines
name,telCode,population,area,gdp,iso2,iso3
Afghanistan,93,"29,121,286","647,500",20.65 Billion,AF,AFG
Albania,355,"2,986,952","28,748",12.8 Billion,AL,ALB
. . .
*/
/* if no 'columns' option, resulting records will look like as below:
[ 'name', 'telCode', 'population', 'area', 'gdp', 'iso2', 'iso3' ]
[ 'Afghanistan',
'93',
'29,121,286',
'647,500',
'20.65 Billion',
'AF',
'AFG' ]
[ 'Albania',
'355',
'2,986,952',
'28,748',
'12.8 Billion',
'AL',
'ALB' ]
*/
/* If 'columns: true' option is given, resulting record of array is json object as below:
{ name: 'Afghanistan',
telCode: '93',
population: '29,121,286',
area: '647,500',
gdp: '20.65 Billion',
iso2: 'AF',
iso3: 'AFG' }
{ name: 'Albania',
telCode: '355',
population: '2,986,952',
area: '28,748',
gdp: '12.8 Billion',
iso2: 'AL',
iso3: 'ALB' }
{ name: 'Algeria',
telCode: '213',
population: '34,586,184',
area: '2,381,740',
gdp: '215.7 Billion',
iso2: 'DZ',
iso3: 'DZA' }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment