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

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

提交回复
热议问题