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
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)