Home > OS >  Convert Json to CSV with specific headers and format
Convert Json to CSV with specific headers and format

Time:01-30

My code recives json from an endpoint and converts it to CSV file.

Can I set specific headers and specific orders I want int this CSV file?

function downloadJSONAsCSV(endpoint) {
    // Fetch JSON data from the endpoint
    fetch(endpoint)
        .then(response => response.json())
        .then(jsonData => {
            // Convert JSON data to CSV
            let csvData = jsonToCsv(jsonData.items.data); // Add .items.data
            // Create a CSV file and allow the user to download it
            let blob = new Blob([csvData], { type: 'text/csv' });
            let url = window.URL.createObjectURL(blob);
            let a = document.createElement('a');
            a.href = url;
            a.download = 'data.csv';
            document.body.appendChild(a);
            a.click();
        })
        .catch(error => console.error(error));
}
function jsonToCsv(jsonData) {
    let csv = '';
    // Get the headers
    let headers = Object.keys(jsonData[0]);
    csv  = headers.join(',')   '\n';
    // Add the data
    jsonData.forEach(function (row) {
        let data = headers.map(header => JSON.stringify(row[header])).join(','); // Add JSON.stringify statement
        csv  = data   '\n';
    });
    return csv;
}

Desired CSV:

"Batch Code","Order Id","Batch Status","Batch Expiration Date","Total","Used","Remaining","Redemption Method","Type","Organization Group","Employee ID","Selection Type"
"B-E7BE5602-2F9B-E3","11608501","Active","2023-06-29","1","0","1","ID CARD","OPEN","Yes","Yes","FLOWER"
"B-480A8929-57D5-97","11608502","Active","2023-06-29","1","0","1","ID CARD","OPEN","No","No","FLOWER"

Json input that I need to convert into CSV:

{
    "numOfItems": {
        "records": 2,
        "data": [{
                "numOfIDs": 1,
                "productId": null,
                "askOrgId": "Yes",
                "orderId": 11608501,
                "orgSelectionType": "FLOWER",
                "batchCode": "B-E7BE5602-2F9B-E3",
                "Type": "OPEN",
                "batchId": 413,
                "creationDate": "2022-06-29",
                "isOnline": "Yes",
                "productName": null,
                "batchProductArray": [{
                        "ID": 663255,
                        "TYPE": "PRODUCT",
                        "NAME": "SomeName"
                    }
                ],
                "numOfUsedPassports": 0,
                "redemptionMethod": "ID Card",
                "askSSN": "No",
                "askEmployeeId": "Yes",
                "batchStatus": "Active",
                "productType": null,
                "expirationDate": "2023-06-29"
            }
        ],
        "draw": 1,
        "recordsTotal": 2
    }
}

I tried to map this json into a specific format but I did not succeded with that.

CodePudding user response:

I would suggest to prepare one array to define property names and order and one array of actual column names. Then code may be something like this:

const data = [{
    "numOfIDs": 1,
    "productId": null,
    "askOrgId": "Yes",
    "orderId": 11608501,
    "orgSelectionType": "FLOWER",
    "batchCode": "B-E7BE5602-2F9B-E3",
    "Type": "OPEN",
    "batchId": 413,
    "creationDate": "2022-06-29",
    "isOnline": "Yes",
    "productName": null,
    "batchProductArray": [{
        "ID": 663255,
        "TYPE": "PRODUCT",
        "NAME": "SomeName"
    }
    ],
    "numOfUsedPassports": 0,
    "redemptionMethod": "ID Card",
    "askSSN": "No",
    "askEmployeeId": "Yes",
    "batchStatus": "Active",
    "productType": null,
    "expirationDate": "2023-06-29"
}
];

const header = ["Batch Code","Order Id"];
const headerProps = ["batchCode", "orderId"]
let csv = header.map(s => "\""   s   "\"").join(",")   "\n";

data.forEach( r => {
    headerProps.forEach((c,i) => csv  = (i>0 ? ", " : "")  "\""  r[c]  "\"")
    csv  = "\n";
})

console.log(csv);

UPDATE: Or as derpirscher pointed out, a simpler version:

data.forEach( r => csv  = headerProps.map(h => `"${r[h]}"`).join(",")   "\n")
  • Related