hi i have this csv file and i want to make it json so i can access data easily in node.js i use the csv-parser module and insted of returning an json/object like file it just returns a big string
‘CountryName,CapitalName,CapitalLatitude,CapitalLongitude,CountryCode,ContinentNamen’ +
‘Somaliland,Hargeisa,9.55,44.050000,NULL,African’ +
‘South Georgia and South Sandwich Islands,King Edward Point,-54.283333,-36.500000,GS,Antarctican’ +
‘French Southern and Antarctic Lands,Port-aux-Français,-49.35,70.216667,TF,Antarctican’ +
‘Palestine,Jerusalem,31.766666666666666,35.233333,PS,Asian’ +
‘Aland Islands,Mariehamn,60.116667,19.900000,AX,Europen’ +
this is example of what it returns (the first row is the headers)
this is the code
const fs = require('fs');
const csv = require('csv-parser');
const dataResults = [];
const fileHeaders = [
'CountryName',
'CapitalName',
'CapitalLatitude',
'CapitalLongitude',
'CountryCode',
'ContinentName'
]
// reads the file
var readFile = fs.createReadStream(__dirname + '/country-capitals.csv','utf-8');
readFile.pipe(csv({separator: 'n', headers:fileHeaders}))
// event handler that handels the data
readFile.on('data', (data)=>dataResults.push(data))
readFile.on('end',()=>{
console.log(dataResults);
})
const fs = require('fs');
const csv = require('csv-parser');
const dataResults = [];
const fileHeaders = [
'CountryName',
'CapitalName',
'CapitalLatitude',
'CapitalLongitude',
'CountryCode',
'ContinentName'
]
// reads the file
var readFile = fs.createReadStream(__dirname + '/country-capitals.csv','utf-8');
readFile.pipe(csv({separator: 'n', headers:fileHeaders}))
// event handler that handels the data
readFile.on('data', (data)=>dataResults.push(data))
readFile.on('end',()=>{
console.log(dataResults);
})
2
Answers
You can use just a simple parse, if I understand what you want to do:
CODE:
RESULT:
source: csv-parse doc
But, if you want to change the property name, like replace ‘CountryName’ key to ‘Name’, take a look at How to rename JSON key
That works for me.