Skip to main content

How to Easily Download JSON Files in Salesforce LWC (With Code Examples)

When building enterprise features in Salesforce Lightning Web Components (LWC), exporting data as a downloadable file is a frequent requirement. Whether you need to export record payloads, configuration settings, or integration logs, generating and downloading JSON files directly in the browser improves user experience without heavy server overhead.

In plain words: You can create and download JSON files client-side in LWC by converting JavaScript objects into a string, wrapping them in a Blob object, and triggering a virtual anchor (<a>) tag click.
Download JSON File in LWC: Code Examples

Prerequisites

  • Basic understanding of LWC structure and JavaScript ES6 syntax.
  • Familiarity with standard browser Web APIs like Blob and URL.createObjectURL().

Method 1: Generating and Downloading In-Memory JSON Data

If your component already holds data in client-side memory, you can convert it to JSON and prompt an immediate download using a dynamic anchor element.

Step-by-Step Procedure:
  1. Serialize the JavaScript object using JSON.stringify().
  2. Create a new Blob instance with type: 'application/json'.
  3. Generate a temporary object URL via URL.createObjectURL().
  4. Programmatically click a hidden anchor element with the download attribute set.
  5. Clean up the URL reference using URL.revokeObjectURL() to prevent memory leaks.
// downloadJSONExample.js
import { LightningElement } from 'lwc';

export default class DownloadJSONExample extends LightningElement {
    downloadJSONFile() {
        const jsonData = {
            appName: 'Salesforce LWC Export',
            timestamp: new Date().toISOString(),
            records: [
                { id: '001XXXXXXXXXXXX1', name: 'Acme Corp' },
                { id: '001XXXXXXXXXXXX2', name: 'Global Tech' }
            ]
        };

        const jsonString = JSON.stringify(jsonData, null, 2);
        const blob = new Blob([jsonString], { type: 'application/json' });
        const url = URL.createObjectURL(blob);

        const link = document.createElement('a');
        link.href = url;
        link.download = 'export-data.json';
        link.click();

        // Release URL object reference from memory
        URL.revokeObjectURL(url);
    }
}

Bind the method to a button in your template HTML file:

<!-- downloadJSONExample.html -->
<template>
    <lightning-card title="Export Data" icon-name="utility:download">
        <div class="slds-m-around_medium">
            <lightning-button 
                label="Download JSON" 
                variant="brand" 
                icon-name="utility:download" 
                onclick={downloadJSONFile}>
            </lightning-button>
        </div>
    </lightning-card>
</template>

Method 2: Fetching JSON from an Endpoint and Downloading

When the target JSON file resides on a remote server or REST endpoint, retrieve it asynchronously using fetch() and execute the same file download workflow once the payload resolves.

// downloadJSONFetchExample.js
import { LightningElement } from 'lwc';

export default class DownloadJSONFetchExample extends LightningElement {
    async downloadRemoteJSON() {
        try {
            const response = await fetch('https://api.example.com/data-endpoint');
            if (!response.ok) {
                throw new Error('Failed to fetch file content');
            }

            const jsonData = await response.json();
            const jsonString = JSON.stringify(jsonData, null, 2);
            
            const blob = new Blob([jsonString], { type: 'application/json' });
            const url = URL.createObjectURL(blob);

            const link = document.createElement('a');
            link.href = url;
            link.download = 'remote-data.json';
            link.click();

            URL.revokeObjectURL(url);
        } catch (error) {
            console.error('Error downloading JSON:', error);
        }
    }
}
Developer Trap: Memory Leaks! Failing to invoke URL.revokeObjectURL(url) keeps generated Blob references active in browser memory. Always release created object URLs after initiating file downloads.
Key Summary: File Exports in LWC
  • Core Method: Combine JSON.stringify(), Blob, and URL.createObjectURL().
  • MIME Type: Explicitly declare { type: 'application/json' } when initializing the Blob.
  • Trigger Mechanism: Instantiate an in-memory <a> element, assign download and href properties, and invoke .click().
  • Cleanup: Call URL.revokeObjectURL() immediately after triggering the click event.

Conclusion

Exporting JSON files directly from Lightning Web Components provides a smooth data export mechanism for Salesforce users. By combining native Web APIs like Blob and URL.createObjectURL(), you can build reliable file download functionality without writing server-side file management logic.