Node.js generated csv file is displaying £ for a UK pound sign (£)

Viewed 2991

I'm using this json2scv package parsing my data (sample json data is described in below code)

I am trying to generate a CSV file in my nodejs application using the code below:

If I open the file in Excel, then I get £ wherever a £ sign should appear.

var json2csv = require('json2csv');
var fs = require('fs');
var fields = ['car', 'price', 'color'];
var myCars = [
  {
    "car": "Audi",
    "price": "£40000",
    "color": "blue"
  }, {
    "car": "BMW",
    "price": "£35000",
    "color": "black"
  }, {
    "car": "Porsche",
    "price": "£60000",
    "color": "green"
  }
];
var csvStr = json2csv({ data: myCars, fields: fields, del: ',' });

fs.writeFile('file.csv', csvStr, { encoding: 'utf8' },function(err) {
  if (err) throw err;
  console.log('file saved');
});

Any Thoughts ?

Thanks.

2 Answers

in 2022 answer

(using changed), call Parser class from json2csv lib

const { Parser } = require('json2csv');

const myCars = [
  {
    "car": "Audi",
    "price": 40000,
    "color": "blue"
  }, {
    "car": "BMW",
    "price": 35000,
    "color": "black"
  }, {
    "car": "Porsche",
    "price": 60000,
    "color": "green"
  }
];

const json2csvParser = new Parser();
const csv = json2csvParser.parse(myCars);

console.log(csv);

With delemiter:

const json2csvParser = new Parser({ delimiter: '\t' });
const tsv = json2csvParser.parse(myCars);

With fields

const fields = ['carModel', 'price', 'colors'];
const json2csvParser = new Parser({ fields, transforms });
const csv = json2csvParser.parse(myCars);

More eamples here

Related