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), "json-file-name.json", "text/plain");

Blob is a file like object of immutable, raw data, they can be read as text or binary data.
URL.createObjectURL() method converts the blob into a URL.

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 "json-file-name.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.