json2csv


json2csv就是 json to csv,能夠將JSON格式的數據轉換成帶標題的CSV格式文件。

先安裝並引用,還記得怎麼操作嗎?

先安裝

npm i json2csv --save

接著引用

var json2csv = require('json2csv');

範例程式碼

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 csv = json2csv({ data: myCars, fields: fields });

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

產生的file.csv檔案內容如下:

"car","price","color"
"Audi",40000,"blue"
"BMW",35000,"black"
"Porsche",60000,"green"

可以用Excel打開,就會是美美的表格了。


 老師!我的表格有亂碼!

人生總是沒這麼順遂,如果你的json資料包含中文,中文就會變亂碼,要處理這個問題我們必須使用iconv-lite這個套件,一樣要先安裝再引用。

先安裝

npm i iconv-lite --save

接著引用

var iconv = require('iconv-lite');

範例程式碼

var json2csv = require('json2csv');
var iconv = require('iconv-lite');
var fs = require('fs');

var fields = ['car', 'price', 'color'];//這裡的內容是不支持中文的。
var myCars = [
  {
    "car": "奧迪",
    "price": 40000,
    "color": "藍色"
  }, {
    "car": "寶馬",
    "price": 35000,
    "color": "黑色"
  }, {
    "car": "保時捷",
    "price": 60000,
    "color": "綠色"
  }
];

var csv = json2csv({ data: myCars, fields: fields });
var newCsv = iconv.encode(csv, 'BIG5'); // 轉碼big-5,簡體用GBK

fs.writeFile('file-chinese.csv', newCsv, function(err) {
  if (err) throw err;
  console.log('file saved');
});

results matching ""

    No results matching ""