Let's assume that you have the following object:
jsxlet person = { name: 'Erik', age: 29, location: 'Barcelona' }
If you want to download it as a JSON file:
jsxlet 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:
terminalnpm i --save file-saver
Use:
jsximport { 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.