Download data in JSON using pure JavaScript or FileSaver.js

Let's assume that you have the following object:

jsx
let person = {
    
    name: 'Erik',
    age: 29,
    location: 'Barcelona'
    
} 

If you want to download it as a JSON file:

jsx
let fileName = 'person.json';

let fileToSave = new Blob([JSON.stringify(person, null, 4)], {
    type: 'application/json',
    name: fileName
});

window.saveAs(fileToSave, fileName);

As window.saveAs is not compatible with all browsers, you can use FileSaver.js to achieve the same results:

Installation:

terminal
npm i --save file-saver

Use:

jsx
import { saveAs } from 'file-saver';

let fileName = 'person.json';

let fileToSave = new Blob([JSON.stringify(person, null, 4)], {
    type: 'application/json',
    name: fileName
});

saveAs(fileToSave, fileName);

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.