Reputation: 1227
I use csvtojson convertor to convert in json format.
var csvFileName = path; //path== filepath
var csvConverter = new Converter();
csvConverter.on("end_parsed", function (jsonObj) {
console.log('in json object', jsonObj);
});
csvConverter.from(csvFileName);
I use bulk export and import of data in csv file.If I just import csv file without changing exported csv file then csvtojson parser parse data in json form correctelly .like
{ csvRows:
[ { id: '51f21e7c60c058bc54000001',
name: 'dummy product',
alias: 'dummy-product1111111111',
description: 'Lorem Ipsumuuu',
images: '',
price: '55',
compare_price: 'undefined',
collections: 'undefined',
brand: 'undefined',
quantity: 'undefined',
sku: 'undefined',
barcode: 'undefined',
categories: '',
publish: '1',
variants: undefined,
state: undefined,
avg_rating: undefined,
num_reviews: undefined,
weight: undefined,
free_product: undefined,
option_set: undefined }]
but when I modify csv file and export then csvtojson parser parser data in this formate -
{ csvRows:
[ { { 'id\tname\talias\tdescription\timages\tprice\tcompare_price\tcollections\tbrand\tquantity\tsku\tbarcode\tcategories\tpublish\tvariants\tstate\tavg_rating\tnum_reviews\tweight\tfree_product\toption_set': '525ba1b3f96404a56a000006\tbraclet12\tbraclet12\tundefined\t\t100\tundefined\tundefined\tundefined\tundefined\tundefined\tundefined\tundefined\t\t\t\t\t\t\t\t' }];
Is there any way to parse csv file data into json form correctelly.
thanks.
Upvotes: 0
Views: 1173
Reputation: 12072
You can use the following js file via terminal. I think it's self explanatory. If not, please write a comment and I'll explain.
'use strict';
var fs = require('fs'),
args = process.argv.slice(2),
seperator = ',',
input = fs.readFileSync('input.csv', {encoding: 'UTF-8'}),
lines = input.split('\n'),
output = [],
props = lines.shift().trim().split(seperator),
i, j,
values,
obj;
for (i = 0; i < args.length - 1; i++) {
if (args[i] === '-s' || args[i] === '--seperator') {
seperator = args[i + 1];
}
}
for (i = 0; i < lines.length; i++) {
if (lines[i].length > 0) {
obj = {};
values = lines[i].split(seperator);
for (j = 0; j < props.length; j++) {
obj[props[j]] = values[j];
}
output.push(obj);
}
}
fs.writeFileSync('output.json', JSON.stringify(output), {encoding: 'UTF-8'});
Upvotes: 1