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

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

    I wanted to riff off @Christian Landgren's answer above. I was confused why my CSV file only had 3 columns/headers. This was because the first element in my json only had 3 keys. So you need to be careful with the const header = Object.keys(json[0]) line. It's assuming that the first element in the array is representative. I had messy JSON that with some objects having more or less.

    So I added an array.sort to this which will order the JSON by number of keys. So that way your CSV file will have the max number of columns.

    This is also a function that you can use in your code. Just feed it JSON!

    function convertJSONtocsv(json) {
        if (json.length === 0) {
            return;
        }
    
        json.sort(function(a,b){ 
           return Object.keys(b).length - Object.keys(a).length;
        });
    
        const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
        const header = Object.keys(json[0])
        let csv = json.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
        csv.unshift(header.join(','))
        csv = csv.join('\r\n')
    
        fs.writeFileSync('awesome.csv', csv)
    }
    

提交回复
热议问题