How to convert JSON array to CSV using Node.js?

前端 未结 4 1459
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 13:49

I want to convert json which has value array. response.json

{
\"rows\": [
[
  \"New Visitor\",
  \"(not set)\",
  \"(not set)\",      
  \"0\"
]         


        
4条回答
  •  长情又很酷
    2021-02-05 14:02

    I don't know about you guys, but i like small packages that just work as expected without a lot of extra configuration, try using jsonexport, i think its the best module for this, works really well with objects, arrays, .. and its fast!

    Install

    npm i --save jsonexport
    

    Usage

    const jsonexport = require('jsonexport');
    const fs = require('fs');
    
    jsonexport([{
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "0"
    },
    {
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "mobile"
    },
    {
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "mobile"
    },
    {
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "mobile",
    }], function(err, csv) {
      if (err) return console.error(err);
      fs.writeFile('output.csv', csv, function(err) {
        if (err) return console.error(err);
        console.log('output.csv saved');
      });
    });
    

    https://github.com/kauegimenes/jsonexport

提交回复
热议问题