0

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.

1
  • Since the value is undefined you are getting the empty objects inside the array. Commented May 17, 2018 at 9:38

2 Answers 2

1

Your loop has some mistakes. You want:

f.forEach(function(d) {
    // Loop through each row
    console.log(x + "============");
    row = d.split(",")
    for (var i = 1; i < row.length; i++) {
        var tmp = {};
        tmp[row[0]] = row[i];
        json.push(tmp);
    }
    x++;
});

You were defining tmp outside of the inner loop, so even though you were changing the value assigned to the id in each iteration, you were making changes to the same object reference. The reason it was coming out as undefined is because you were iterating to <= row.length, and row[row.length] returns undefined.

Oh and just FYI, x = x++ essentially does nothing. x++ increments x as a side-effect but evaluates to x's original value, which you are then assigning back to x.

Sign up to request clarification or add additional context in comments.

1 Comment

maybe add a little explanation about what errors were made exactly.
0

Step 1:

Install node module: npm install csvtojson --save

Step 2:

var Converter = require("csvtojson").Converter;

var converter = new Converter({});

converter.fromFile("./path-to-your-file.csv",function(err,result){

   if(err){
      console.log("Error");
      console.log(err);  
   } 
   var data = result;

   //to check json
   console.log(data);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.