How to export JSON to CSV using JavaScript/jQuery ?

 

Exporting JSON data to a CSV (Comma-Separated Values) file using JavaScript or jQuery can be achieved by following these steps:


1. Prepare the JSON Data: Ensure you have the JSON data that you want to export to a CSV file.


2. Convert JSON to CSV Format: Write a function to convert the JSON data into CSV format. CSV format consists of comma-separated values with line breaks for each row.


3. Create a Download Link: Create a download link for the CSV file and trigger the download programmatically.


Below is a step-by-step guide on how to achieve this:


HTML


<!DOCTYPE html>

<html>

<head>

    <title>Export JSON to CSV</title>

</head>

<body>

    <button id="exportButton">Export JSON to CSV</button>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script src="script.js"></script>

</body>

</html>


JavaScript (script.js)


// Sample JSON data (replace this with your actual JSON data)

const jsonData = [

    { name: "John Doe", age: 30, email: "john@example.com" },

    { name: "Jane Smith", age: 25, email: "jane@example.com" },

    // Add more data here if needed

];


// Function to convert JSON to CSV format

function convertJSONToCSV(jsonData) {

    const separator = ",";

    const lineBreak = "\n";


    // Extract the keys from the first object to use as CSV headers

    const headers = Object.keys(jsonData[0]);


    // Create CSV content

    let csvContent = headers.join(separator) + lineBreak;


    jsonData.forEach((data) => {

        const row = headers.map((header) => data[header]);

        csvContent += row.join(separator) + lineBreak;

    });


    return csvContent;

}


// Function to trigger CSV download

function downloadCSV(csvContent) {

    const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });

    const url = URL.createObjectURL(blob);

    const link = document.createElement("a");

    link.setAttribute("href", url);

    link.setAttribute("download", "data.csv");

    link.style.display = "none";

    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);

}


// Event listener for the export button click

$("#exportButton").on("click", function () {

    // Convert JSON to CSV format

    const csvContent = convertJSONToCSV(jsonData);


    // Trigger CSV download

    downloadCSV(csvContent);

});


Explanation


1. The HTML file contains a button with the id "exportButton", which will be used to trigger the JSON to CSV export.


2. In the JavaScript file, we have a sample JSON data stored in the `jsonData` variable. Replace this data with your actual JSON data.


3. The `convertJSONToCSV` function takes the JSON data and converts it into CSV format. It first extracts the keys (headers) from the first object in the JSON data. Then, it iterates through the JSON data to create rows in the CSV content by joining the values with commas.


4. The `downloadCSV` function creates a Blob (Binary Large Object) with the CSV content and generates a download link for the CSV file. It programmatically clicks the link to initiate the download and then removes the link from the document.


5. The event listener is set up to trigger the CSV export when the "Export JSON to CSV" button is clicked. It calls the `convertJSONToCSV` function to get the CSV content and then calls the `downloadCSV` function to initiate the download.


That's it! Now, when you click the "Export JSON to CSV" button, the JSON data will be converted into a CSV file and automatically downloaded to the user's device.