JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Json To CSV</title>
</head>
<body>
<h1>Hi!</h1>
</body>
</html>
JavaScript
var data = [
{
"id": "111",
"name": "Johny Smith",
"age": "23",
"dates": [
{
"birthday": "01.01.1990",
"nameday": "02.02",
"phone": {
"home": "02123123123123",
"mobile": "07124123123",
}
}
]
},
{
"id": "111",
"name": "Jane Alex",
"age": "43",
"dates": [
{
"birthday": "06.06.1997",
"nameday": "03.03",
"phone": {
"home": "029999999999999",
"mobile": "0788888888",
}
}
]
}
];
// Converted string ready to be downloaded as csv
var converted = toCsv(data);
// This is used to automatically generate and download the .CSV file
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(converted));
element.setAttribute('download', "Output.csv");
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
function toCsv(arr) {
arr = pivot(arr);
return arr.map(function (row) {
return row.map(function (val) {
return isNaN(val) ? JSON.stringify(val) : +val;
}).join(',');
}).join('\n');
}
function toConsumableArray(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
...