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

前端 未结 6 791
青春惊慌失措
青春惊慌失措 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:05

    You can also direct json2csv to use a sub array within your JSON object by addressing it with . after your JSON object in the data section of json2csv.

    In your case, this might look something like:

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

提交回复
热议问题