Converting JSON object to CSV format in JavaScript

前端 未结 9 708
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 04:37

I am trying to convert a JavaScript object set in to CSV format

You can get the idea about my Javascript object, if you put it in online JSON parser http://json.pars

相关标签:
9条回答
  • 2020-11-30 05:20

    This is a quick & dirty, but probably works for most cases:

    const headers = Object.keys(objAry[0])
    console.log(headers.join())
    
    objAry.forEach(r => console.log(
       Object.values(r)
       .map(c => Array.isArray(c)? `"${c.join()}"` : c)
       .join())
    )
    
    0 讨论(0)
  • 2020-11-30 05:21

    Below code will convert and download JSON array to csv as a file.

     function exportJSONToCSV(objArray) {
        var arr = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
        var str =
          `${Object.keys(arr[0])
            .map((value) => `"${value}"`)
            .join(',')}` + '\r\n';
        var csvContent = arr.reduce((st, next) => {
          st +=
            `${Object.values(next)
              .map((value) => `"${value}"`)
              .join(',')}` + '\r\n';
          return st;
        }, str);
        var element = document.createElement('a');
        element.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
        element.target = '_blank';
        element.download = 'export.csv';
        element.click();
      }
    
    0 讨论(0)
  • 2020-11-30 05:23

    Here's a solution similar to mightybruno's answer that handles strings containing commas. None of the other answers seem to take this in to consideration.

    function objectsToCSV(arr) {
        const array = [Object.keys(arr[0])].concat(arr)
        return array.map(row => {
            return Object.values(row).map(value => {
                return typeof value === 'string' ? JSON.stringify(value) : value
            }).toString()
        }).join('\n')
    }
    
    0 讨论(0)
提交回复
热议问题