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

前端 未结 4 1457
佛祖请我去吃肉
佛祖请我去吃肉 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:00

    Do it yourself like this:

    'use strict';
    
    var fs = require('fs');
    
    let myObj = {
      "rows": [
        [
          "New , Visitor",
          "(not set)",
          "(not set)",
          "0"
        ],
        [
          "New Visitor",
          "(not set)",
          "(not set)",
          "mobile"
        ],
        [
          "New Visitor",
          "(not set)",
          "(not set)",
          "mobile"
        ],
        [
          "New Visitor",
          "(not set)",
          "(not set)",
          "mobile",
        ]
      ]
    }
    
    // 1. One way - if you want the results to be in double quotes and you have comas inside
    
    // choose another string to temporally replace commas if necessary
    let stringToReplaceComas = '!!!!';
    
    myObj.rows.map((singleRow) => {
      singleRow.map((value, index) => {
        singleRow[index] = value.replace(/,/g, stringToReplaceComas);
      })
    })
    
    let csv = `"${myObj.rows.join('"\n"').replace(/,/g, '","')}"`;
    // // or like this
    // let csv = `"${myObj.rows.join('"\n"').split(',').join('","')}"`;
    
    csv = csv.replace(new RegExp(`${stringToReplaceComas}`, 'g'), ',');
    
    // // 2. Another way - if you don't need the double quotes in the generated csv and you don't have comas in rows' values
    // let csv = myObj.rows.join('\n')
    
    fs.writeFile('name.csv', csv, 'utf8', function(err) {
      if (err) {
        console.log('Some error occured - file either not saved or corrupted file saved.');
      } else {
        console.log('It\'s saved!');
      }
    });
    

    Use libraries

    ex. https://github.com/mrodrig/json-2-csv, https://github.com/wdavidw/node-csv, https://github.com/wdavidw/node-csv-stringify

    an example using json-2-csv (https://github.com/mrodrig/json-2-csv)

    'use strict';
    
    const converter = require('json-2-csv');
    
    let myObj = {
      "rows": [
        {
          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",
        }
      ]
    }
    
    let json2csvCallback = function (err, csv) {
        if (err) throw err;
        fs.writeFile('name.csv', csv, 'utf8', function(err) {
          if (err) {
            console.log('Some error occured - file either not saved or corrupted file saved.');
          } else {
            console.log('It\'s saved!');
          }
        });
    };
    
    converter.json2csv(myObj.rows, json2csvCallback, {
      prependHeader: false      // removes the generated header of "value1,value2,value3,value4" (in case you don't want it)
    });
    

    an example using csv-stringify (https://github.com/wdavidw/node-csv-stringify)

    'use strict';
    
    var stringify = require('csv-stringify');
    var fs = require('fs');
    
    let myObj = {
      "rows": [
        [
          "New Visitor",
          "(not set)",
          "(not set)",
          "0"
        ],
        [
          "New Visitor",
          "(not set)",
          "(not set)",
          "mobile"
        ],
        [
          "New Visitor",
          "(not set)",
          "(not set)",
          "mobile"
        ],
        [
          "New Visitor",
          "(not set)",
          "(not set)",
          "mobile",
        ]
      ]
    }
    
    stringify(myObj.rows, function(err, output) {
      fs.writeFile('name.csv', output, 'utf8', function(err) {
        if (err) {
          console.log('Some error occured - file either not saved or corrupted file saved.');
        } else {
          console.log('It\'s saved!');
        }
      });
    });
    

提交回复
热议问题