I have a set of JSON format as below. During converting from JSON to CSV, the function is worked but not all key
is exist in the CSV file. How to allow all the key
available in the CSV file?
Reference: How to convert JSON to CSV format and store in a variable
JSON
var data={
"items": [
{
"bandwidth": "",
"destination_ipv4": "",
"destination_ipv6": ""
},
{
"interface": "",
"alarm": false,
"service": [
]
},
{
"unit": {
"name": "operation",
"shaping-rate": {
"rate": "1G"
}
},
"ipv6_address": ""
},
{
"vrf": ""
}
]
};
JS
function download_file(data) {
const items = data.items
const replacer = (key, value) => value === null ? '' : value
const header = Object.keys(items[0])
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
var link = document.createElement("a");
link.id="lnkDwnldLnk";
document.body.appendChild(link);
blob = new Blob([csv], { type: 'text/csv' });
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = 'Result.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}