How to convert JSON to CSV format and store in a variable

前端 未结 16 2360
一整个雨季
一整个雨季 2020-11-22 17:31

I have a link that opens up JSON data in the browser, but unfortunately I have no clue how to read it. Is there a way to convert this data using JavaScript in CSV format and

16条回答
  •  半阙折子戏
    2020-11-22 17:33

    I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.

    I use $.getJSON to pull json data from an external page, but if you have a basic array, you can just use that.

    This uses Christian Landgren's code to create the csv data.

    $(document).ready(function() {
        var JSONData = $.getJSON("GetJsonData.php", function(data) {
            var items = data;
            const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
            const header = Object.keys(items[0]);
            let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
            csv.unshift(header.join(','));
            csv = csv.join('\r\n');
    
            //Download the file as CSV
            var downloadLink = document.createElement("a");
            var blob = new Blob(["\ufeff", csv]);
            var url = URL.createObjectURL(blob);
            downloadLink.href = url;
            downloadLink.download = "DataDump.csv";  //Name the file here
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        });
    });
    

    Edit: It's worth noting that JSON.stringify will escape quotes in quotes by adding \". If you view the CSV in excel, it doesn't like that as an escape character.

    You can add .replace(/\\"/g, '""') to the end of JSON.stringify(row[fieldName], replacer) to display this properly in excel (this will replace \" with "" which is what excel prefers).

    Full Line: let csv = items.map(row => header.map(fieldName => (JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""'))).join(','));

提交回复
热议问题