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: "",
 website: ""

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

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

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


© 2019 4codev

Created with love by Sil.