Download JSON File in LWC

by Rijwan Mohmmed
download-json-file-in-lwc-techdicer

Hello friends, today we will explore how to Download JSON File in LWC. Whether you want to export data for offline analysis or provide users with the ability to download data from your LWC application, generating and downloading JSON files is a valuable capability to have.
JSON files store data in a structured format using key-value pairs. It is widely used for representing complex data objects, making it an ideal choice for transmitting data between systems.

Also, check this: Upload CSV and Create Records in LWC

Key Highlights :

  1. JSON (JavaScript Object Notation) has become a popular format for data interchange due to its simplicity and compatibility with various programming languages.
  2. The ability to download JSON files enhances user experience, promotes data interoperability, and allows for further analysis and collaboration.

Code :

AccountDataController.cls :

public class AccountDataController {

    @AuraEnabled(Cacheable = false)
    public static List<Account> getAccounts(){
      return [SELECT Id, Name,Industry, Type, Phone, Rating, AccountNumber FROM Account ORDER BY Name LIMIT 10];
    }
}

DownloadJSONLWC.HTML :

<template>
    <lightning-button variant="brand" label="Download JSON" title="DownloadJSON" onclick={handleJSONDonwload}></lightning-button>
</template>

DownloadJSONLWC.JS:

import { LightningElement, api, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getAccounts from '@salesforce/apex/AccountDataController.getAccounts';

export default class DownloadJSONLWC extends LightningElement {
    @track data;

    handleJSONDonwload() {
        this.handleFetchJSONData();
    }

    handleFetchJSONData() {
        getAccounts({})
            .then(res => {
                console.log(res);
                this.data = JSON.stringify(res);
                this.handleDownloadJSONFile();
            }).catch(err => {
                this.showToast('Error', err.body.message, 'error', 'dismissable');
            })
    }

    handleDownloadJSONFile() {
        let data = this.data;
        let self = this;
        // Creating anchor element to download
        let downloadElement = document.createElement('a');

        // This  encodeURI encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).
        downloadElement.href = 'data:text/json;charset=utf-8,' + encodeURI(data);
        downloadElement.target = '_self';
        // CSV File Name
        downloadElement.download = 'AccountData.JSON';
        // below statement is required if you are using firefox browser
        document.body.appendChild(downloadElement);
        // click() Javascript function to download CSV file
        downloadElement.click();

        self.showToast('Success', 'Download file successfully!!', 'success', 'dismissable');
        self.isExecuting = false;
    }

    showToast(title, message, variant, mode) {
        const evt = new ShowToastEvent({
            title: title,
            message: message,
            variant: variant,
            mode: mode
        });
        this.dispatchEvent(evt);
    }
}

DownloadJSONLWC.JS-meta.xml:

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>57.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

download-json-file-in-lwc-techdicer
download-json-file-in-lwc-techdicer

Reference :

  1. LWC
What’s your Reaction?
+1
2
+1
0
+1
0
+1
0
+1
1
+1
0

You may also like

Leave a Comment