Categories
JavaScript Answers

How to save JSON to local text file with JavaScript?

Spread the love

Sometimes, we want to save JSON to local text file with JavaScript.

In this article, we’ll look at how to save JSON to local text file with JavaScript.

How to save JSON to local text file with JavaScript?

To save JSON to local text file with JavaScript. we can create a blob from the text.

For instance, we write

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

to create a link with createElement.

Then we create a blob with the content string with the Blob constructor.

We set its MIME type to 'text/plain'.

And then we create an object URL from the blob with createObjectURL.

Next, we set the download property to a string with the name of the downloaded file.

Then we call click to download the content text into a file.

Conclusion

To save JSON to local text file with JavaScript. we can create a blob from the text.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *