((new)) Download Json Object As A File From Browser React File
const downloadJson = (data, fileName) => // 1. Stringify the object (with 2-space indentation for readability) const jsonString = JSON.stringify(data, null, 2); // 2. Create a Blob with the JSON data const blob = new Blob([jsonString], type: "application/json" ); // 3. Create a temporary URL for the Blob const url = URL.createObjectURL(blob); // 4. Create an anchor element and click it programmatically const link = document.createElement("a"); link.href = url; link.download = `$fileName.json`; document.body.appendChild(link); link.click(); // 5. Cleanup: remove the link and revoke the URL document.body.removeChild(link); URL.revokeObjectURL(url); ; Use code with caution. 2. Creating a Reusable React Component
: Use JSON.stringify(data, null, 2) to make the downloaded file human-readable. download json object as a file from browser react
Downloading a JSON object as a file in a React application is a common task for exporting data like user reports, configuration settings, or application states. The most efficient way to achieve this without a server is by using the and Object URLs to trigger a browser-level download . 1. The Core Implementation (Vanilla JavaScript) const downloadJson = (data, fileName) => // 1
: If the data is stored in React state , ensure the download function captures the current state accurately. Create a temporary URL for the Blob const url = URL
The logic revolves around converting your JavaScript object into a JSON string, wrapping it in a Blob , and creating a temporary link to trigger the download. javascript
: Always call URL.revokeObjectURL(url) to free up browser memory after the download completes.
How to Export and Download CSV and JSON Files in React | The Road To Enterprise