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

前端 未结 16 2115
一整个雨季
一整个雨季 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:32

    Very nice solution by praneybehl, but if someone wants to save the data as a csv file and using a blob method then they can refer this:

    function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {     
    
    //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = '';    
    //This condition will generate the Label/Header
    if (ShowLabel) {
        var row = "";
    
        //This loop will extract the label from 1st index of on array
        for (var index in arrData[0]) {
            //Now convert each value to string and comma-seprated
            row += index + ',';
        }
        row = row.slice(0, -1);
        //append Label row with line break
        CSV += row + '\r\n';
    }
    
    //1st loop is to extract each row
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        //2nd loop will extract each column and convert it in string comma-seprated
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }
        row.slice(0, row.length - 1);
        //add a line break after each row
        CSV += row + '\r\n';
    }
    
    if (CSV == '') {        
        alert("Invalid data");
        return;
    }   
    
    //this trick will generate a temp "a" tag
    var link = document.createElement("a");    
    link.id="lnkDwnldLnk";
    
    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);
    
    var csv = CSV;  
    blob = new Blob([csv], { type: 'text/csv' }); 
    var csvUrl = window.webkitURL.createObjectURL(blob);
    var filename = 'UserExport.csv';
    $("#lnkDwnldLnk")
    .attr({
        'download': filename,
        'href': csvUrl
    }); 
    
    $('#lnkDwnldLnk')[0].click();    
    document.body.removeChild(link);
    }
    
    0 讨论(0)
  • 2020-11-22 17:32

    Heres a way to do it for dynamically deep objects in a object oriented way for the newer js versions. you might have to change the seperatortype after region.

    private ConvertToCSV(objArray) {
        let rows = typeof objArray !== "object" ? JSON.parse(objArray) : objArray;
        let  header = "";
        Object.keys(rows[0]).map(pr => (header += pr + ";"));
    
        let str = "";
        rows.forEach(row => {
            let line = "";
            let columns =
                typeof row !== "object" ? JSON.parse(row) : Object.values(row);
            columns.forEach(column => {
                if (line !== "") {
                    line += ";";
                }
                if (typeof column === "object") {
                    line += JSON.stringify(column);
                }  else {
                    line += column;
                }
            });
            str += line + "\r\n";
        });
        return header + "\r\n" + str;
    }
    
    0 讨论(0)
  • 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(','));

    0 讨论(0)
  • 2020-11-22 17:33

    Here's my simple version of converting an array of objects ito CSV (assuming those objects all share the same attributes):

    var csv = []
    if (items.length) {
      var keys = Object.keys(items[0])
      csv.push(keys.join(','))
      items.forEach(item => {
        let vals = keys.map(key => item[key] || '')
        csv.push(vals.join(','))
      })
    }
    
    csv = csv.join('\n') 
    
    0 讨论(0)
  • 2020-11-22 17:34

    An adaption from praneybehl answer to work with nested objects and tab separator

    function ConvertToCSV(objArray) {
      let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
      if(!Array.isArray(array))
          array = [array];
    
      let str = '';
    
      for (let i = 0; i < array.length; i++) {
        let line = '';
        for (let index in array[i]) {
          if (line != '') line += ','
    
          const item = array[i][index];
          line += (typeof item === 'object' && item !== null ? ConvertToCSV(item) : item);
        }
        str += line + '\r\n';
      }
    
      do{
          str = str.replace(',','\t').replace('\t\t', '\t');
      }while(str.includes(',') || str.includes('\t\t'));
    
      return str.replace(/(\r\n|\n|\r)/gm, ""); //removing line breaks: https://stackoverflow.com/a/10805198/4508758
    }
    
    0 讨论(0)
  • 2020-11-22 17:35

    A more elegant way to convert json to csv is to use the map function without any framework:

    var json = json3.items
    var fields = Object.keys(json[0])
    var replacer = function(key, value) { return value === null ? '' : value } 
    var csv = json.map(function(row){
      return fields.map(function(fieldName){
        return JSON.stringify(row[fieldName], replacer)
      }).join(',')
    })
    csv.unshift(fields.join(',')) // add header column
     csv = csv.join('\r\n');
    console.log(csv)
    

    Output:

    title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id
    "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468"
    "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"
    

    Update ES6 (2016)

    Use this less dense syntax and also JSON.stringify to add quotes to strings while keeping numbers unquoted:

    const items = json3.items
    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')
    
    console.log(csv)
    
    0 讨论(0)
提交回复
热议问题