Simple Json: File ((install)) Download
function downloadJSON(data, filename = 'data.json') { // 1. Convert the JavaScript object to a JSON string // The 'null, 4' arguments create a "pretty-printed" JSON file const jsonString = JSON.stringify(data, null, 4); // 2. Create a Blob with the JSON data const blob = new Blob([jsonString], { type: 'application/json' }); // 3. Create a temporary anchor element const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = filename; // 4. Trigger the download and clean up document.body.appendChild(link); link.click(); document.body.removeChild(link); } // Usage Example: const myData = { name: "John Doe", role: "Developer", active: true }; downloadJSON(myData, 'user-profile.json'); Use code with caution. How It Works:
A doesn't require complex libraries or backend endpoints. By using the JavaScript Blob constructor and a temporary link, you can provide users with a clean, formatted data export in just a few lines of code. simple json file download
Include timestamps in your filenames if the data is dynamic (e.g., report_2023-10-27.json ). This prevents users from overwriting previous downloads. 5. Security Considerations When allowing users to download JSON: function downloadJSON(data, filename = 'data