I've the below content in my text file.
100004990,a122,a128,a169,a2122,a42474
100008935,a41661,a42189,a64407,a8199,a17031,a186,a25199
and using this I want to create a json file and the criteria is key should be the number in start and value should be the other values in the same row like below.
[{"100004990":"a122"},{"100004990":"a128"}......, {"100008935":"a41661"},{"100008935":"a42189"},.....]
I'm using the below code.
// Node packages for file system
var fs = require('fs');
var path = require('path');
var filePath = path.join(__dirname, 'dataservices_statsocial_raw.tsv');
// Read CSV
var f = fs.readFileSync(filePath, { encoding: 'utf-8' },
function(err) { console.log(err); });
// Split on row
f = f.split("\n");
console.log(f.length)
// Get first row for column headers
// headers = f.shift().split(",");
var json = [];
var x = 1;
f.forEach(function(d) {
// Loop through each row
console.log(x + "============");
tmp = {}
row = d.split(",")
for (var i = 1; i <= row.length; i++) {
tmp[row[0]] = row[i];
json.push(tmp);
}
x = x++;
});
console.log(json);
var outPath = path.join(__dirname, 'new.json');
fs.writeFileSync(outPath, JSON.stringify(json), 'utf8',
function(err) { console.log(err); });
but this gives me the output as below in my json file.
[{},{},{},{},{},{},{},{},{},{},{},{},{}]
and In my console I get the output as
2
1============
1============
[ { '100004990': undefined },
{ '100004990': undefined },
{ '100004990': undefined },
{ '100004990': undefined },
{ '100004990': undefined },
{ '100004990': undefined },
{ '100008935': undefined },
{ '100008935': undefined },
{ '100008935': undefined },
{ '100008935': undefined },
{ '100008935': undefined },
{ '100008935': undefined },
{ '100008935': undefined } ]
Please let me know on where am I going wrong.