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

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

    If anyone wanted to download it as well.
    Here is an awesome little function that will convert an array of JSON objects to csv, then download it.

    downloadCSVFromJson = (filename, arrayOfJson) => {
      // convert JSON to CSV
      const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
      const header = Object.keys(arrayOfJson[0])
      let csv = arrayOfJson.map(row => header.map(fieldName => 
      JSON.stringify(row[fieldName], replacer)).join(','))
      csv.unshift(header.join(','))
      csv = csv.join('\r\n')
    
      // Create link and download
      var link = document.createElement('a');
      link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv));
      link.setAttribute('download', filename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };
    

    Then call it like this:

    this.downloadCSVFromJson(`myCustomName.csv`, this.state.csvArrayOfJson)
    

提交回复
热议问题