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

前端 未结 16 2306
一整个雨季
一整个雨季 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: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') 
    

提交回复
热议问题