How to parse JSON object to CSV file using json2csv nodejs module

前端 未结 6 818
青春惊慌失措
青春惊慌失措 2020-12-10 07:44

I\'m currently learning how to parse a JSON object to a CSV file using the json2csv node module. Have never worked with JSON before, so this is all new to me.

My JSO

6条回答
  •  半阙折子戏
    2020-12-10 08:01

    The input is bad format, it should like json2csv document:

    var json2csv = require('json2csv');
    
    var json = [
      {
        "car": "Audi",
        "price": 40000,
        "color": "blue"
      }, {
        "car": "BMW",
        "price": 35000,
        "color": "black"
      }, {
        "car": "Porsche",
        "price": 60000,
        "color": "green"
      }
    ];
    
    json2csv({data: json, fields: ['car', 'price', 'color']}, function(err, csv) {
      if (err) console.log(err);
      fs.writeFile('file.csv', csv, function(err) {
        if (err) throw err;
        console.log('file saved');
      });
    });
    

    The content of the "file.csv" should be

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

提交回复
热议问题