JSON file to CSV download with vanilla JavaScript

OpenJavaScript 0

Last updated: January 5, 2023.

To make the conversion from JSON to CSV, first fetch the JSON data by making a HTTP request. If you are using the native fetch method, you can call res.json() on the response object to convert it from JSON to a JavaScript object.

Then, you want to extract the keys from one of the objects in the array. These will form the first row in the CSV file.

Then, do the same for the values within each object. For this, you will need to employ an iterative method, such as map() in the example below.

Finally, the row of keys and and all the rows of values should be merged into one array.

Standard CSV format is to have column values separated by a comma and rows by a link break (‘\n‘):

fetch('https://reqres.in/api/users')
    .then(res => res.json()) // Reads readable stream to JS object
    .then(obj => handle(obj))
    

function handle(obj) {

    // Data on 'obj' is stored on 'data' property

    const headers = Object.keys(obj.data[0]).toString();
    // Get and stringify the keys of the first object in the array

    const main = obj.data.map((item) => {
    // Iterates through each object

        return Object.values(item).toString();
        // Returns an array of the values of the current item 

    });
    // Map finally returns array of arrays of values in each object

    const csv = [headers, ...main].join('\n');
    // Creates new array, where first row is keys and further rows the values in each object

    console.log(csv);
    // id,email,first_name,last_name,avatar
    // 1,george.bluth@reqres.in,George,Bluth,https://reqres.in/img/faces/1-image.jpg
    // 2,janet.weaver@reqres.in,Janet,Weaver,https://reqres.in/img/faces/2-image.jpg
    // 3,emma.wong@reqres.in,Emma,Wong,https://reqres.in/img/faces/3-image.jpg
    // 4,eve.holt@reqres.in,Eve,Holt,https://reqres.in/img/faces/4-image.jpg
    // 5,charles.morris@reqres.in,Charles,Morris,https://reqres.in/img/faces/5-image.jpg
    // 6,tracey.ramos@reqres.in,Tracey,Ramos,https://reqres.in/img/faces/6-image.jpg

}

After the data has been formatted in CSV format, convert it to Blob format and create a temporary URL to it using window.createObjectURL(theBlob).

Then, you can use this URL to set the href attribute of an anchor element whose type is set to download.

Unless you want the download to start automatically, you'll want to make the entire process on a user interaction, such as a button click below:

<h1>JSON to CSV file download</h1>

<button id="btn">Start Download</button>

<script>

fetch('https://reqres.in/api/users')
    .then(res => res.json())
    .then(obj => handle(obj))
    
function handle(obj) {

    const headers = Object.keys(obj.data[0]).toString();

    const main = obj.data.map((item) => {

        return Object.values(item).toString();

    });

    const csv = [headers, ...main].join('\n');

    startCSVDownload(csv);

}

function startCSVDownload(input) {

    const blob = new Blob([input], { type: 'application/csv' });
    // Creates new CSV blob (a file)

    const url = URL.createObjectURL(blob);
    // Creates a temporary URL to the blob in the brwoser

    document.getElementById('btn').addEventListener('click', () => {
    // When the button is clicked...

        const a = document.createElement('a');
        a.download = 'users.csv';
        a.href = url;
        a.style.display = 'none';
        //... Set temporary URL as href of anchor element...

        document.body.appendChild(a);
        a.click();
        a.remove();
        //...insert in DOM, simulate a click and remove....

        URL.revokeObjectURL(url);
        //...remove URL (also remove linked file from browser memory)

    })

}

</script>

Related posts