Abhinav
Abhinav

Reputation: 1027

nodejs - csvtojson not giving proper json keys in output

I am using csvtojson package in nodejs. I have written below code to convert my csv file but it is not converting into json properly. The keys in json do not have double brackets hence I am not able to get value using key.

var Converter = require("csvtojson").Converter;
var converter = new Converter({});

converter.fromFile("./file.csv", function(err,result){
    console.log(result);
});

Output shown is as below:

[ { a: 1, b: 2, c: 3 }, { a: 3, b: 4, c: 5 } ]

Hence it gives error as "Key not found!! c"

Can someone help.

The csv content is as below:

a,b,c
1,2,3
3,4,5

Upvotes: 0

Views: 1032

Answers (2)

DrakaSAN
DrakaSAN

Reputation: 7853

From the documentation, it seems the output should be [{"a": 1, "b": 2, "c": 3}, {"a": 3, "b": 4, "c": 5}], which is a JSON string.

To access the property of the objects, you would need to evaluate it with JSON.parse.

Another error could be in how you access c, but you didn't show the code for that.

Upvotes: 1

Franck
Franck

Reputation: 33

console.log doesn't give you json formatted output, it is the dump of the javascript object, formatting is different.

You need to address the results line by line. Your result is an array, each item being a line with all the fields. So you can address the first line's c key with :

result[0]['c']

Or you probably want to loop into this array to access each line :

converter.fromFile("./file.csv", function(err,result){
    for (var i in result) {
        var line=result[i];
        console.log("line "+i+":" + line.c);
    }
 });    

Upvotes: 0

Related Questions