Sunday, 7 May 2017

Why does a loaded CSV set the value of object to a string

So I have this code:

function _getAllArticles() {
    var result = [];
    result.push(new Article('./BatmanEpicWallpaper.jpg','Batman','A poster of batman', 100, 34.99));
    result.push(new Article('./BatmanEpicWallpaper.jpg', 'Batman2', 'A poster of batman2', 10, 124.99));
    result.push(new Article('./BatmanEpicWallpaper.jpg', 'Batman3', 'A poster of batman3', 25, 4.99));

    var converter = require('json-2-csv');
    var fs = require('fs')

    var test = [];

    converter.json2csv(result, function (err, csv) {
        if (err) console.log(err);
        console.log(csv);
        test.push(csv);
    })
    fs.writeFile('file.csv', test, function (err) {
        if (err) throw err;
        console.log('file saved');
    });



    var fs = require('fs')
    var csvjson = require('csvjson');
    var data = fs.readFileSync('file.csv', { encoding: 'utf8' });
    return csvjson.toObject(data);
}

As you can see I have object article where there are two attributes with numbertypes. But when I load the file the values of the attributes quantity and price are converted to a string. When I exceute this line of codereturn csvjson.toObject(data); and JSON.stringify it I get this:

[{"imageLocation":"./BatmanEpicWallpaper.jpg","title":"Batman","description":"A poster of batman","quantity":"34.99","price":"100"},{"imageLocation":"./BatmanEpicWallpaper.jpg","title":"Batman2","description":"A poster of batman2","quantity":"124.99","price":"10"},{"imageLocation":"./BatmanEpicWallpaper.jpg","title":"Batman3","description":"A poster of batman3","quantity":"4.99","price":"25"}]

As you can see the value of the attribute quantity and price are always with "" why is that so? Is it because of modules which I use (json-2-csv,csvjson)?



via TiZaLjubavNisiRodjena

No comments:

Post a Comment