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

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

    Sometimes objects have different lengths. So I ran into the same problem as Kyle Pennell. But instead of sorting the array we simply traverse over it and pick the longest. Time complexity is reduced to O(n), compared to O(n log(n)) when sorting first.

    I started with the code from Christian Landgren's updated ES6 (2016) version.

    json2csv(json) {
        // you can skip this step if your input is a proper array anyways:
        const simpleArray = JSON.parse(json)
        // in array look for the object with most keys to use as header
        const header = simpleArray.map((x) => Object.keys(x))
          .reduce((acc, cur) => (acc.length > cur.length ? acc : cur), []);
    
        // specify how you want to handle null values here
        const replacer = (key, value) => (
          value === undefined || value === null ? '' : value);
        let csv = simpleArray.map((row) => header.map(
          (fieldName) => JSON.stringify(row[fieldName], replacer)).join(','));
        csv = [header.join(','), ...csv];
        return csv.join('\r\n');
    }
    

提交回复
热议问题