Download / save JSON content to local file in Javascript

How do you save an JSON content to local file? In Javascript we do that so easily, let us show you!

Step 1: Add some Javascript codes below

const jsonData = {
 name: "Jonth",
 email: "jobtd@mail.com",
 website: "www.4codev.com"
};

function download(content, fileName, contentType) {
 const a = document.createElement("a");
 const file = new Blob([content], { type: contentType });
 a.href = URL.createObjectURL(file);
 a.download = fileName;
 a.click();
}

function onDownload(){
 download(JSON.stringify(jsonData), "yourfile.json", "text/plain");
}
Copy this code

In this Javascript codes, jsonData is the content that you want to save to local file.
onDownload is a function will be call when the download button clicked. Inside of this function, you can change "yourfile.json" from .json to .txt if you want to save it as a text file.

Step 2: add download button with HTML code below

 <button onclick="onDownload()">Download</button>

Copy this code


Click download button to view the result in demo below: