Menu Close

Download Json array as File using Jquery

In this article we are going to discuss how to download JSON array as File using Jquery. In some scenario we need to download json file in browser itself, top follow this article we will discuss how easily we do it. Please read my previous article Angular 10 with ASP.NET Web API-CRUD Operations.

What We do here ?

In this example we create a JSON object then convert it into a JSON String and then to BLOB object, then downloaded as Text file from Browser using jQuery.

HTML Markup

Here we simply create a HTML page and create a button and on the button onclick() event we call the javascript function and there create a dummy json array and download the file.

<input type="button" value="Download Json" onclick="DownloadJson()" />

Downloading JSON array as File using jQuery

The JSON string is converted into a BLOB object which is later downloaded as text file using jQuery. The blow are the Javascript function that call when button Onclick() method is called.

<script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">
        function DownloadJson() {
            var studentList = [
                { "Name": "John", "score": "30" },
                { "Name": "Rozi", "score": "40" },
                { "Name": "Peter", "score": "50" },
                { "Name": "Finch", "score": "60" },
                { "Name": "Ravi", "score": "70" }
            ];
            //Convert JSON Array to string.
            var json = JSON.stringify(studentList);
            var blob = new Blob([json]);
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = "studentList.txt";
            link.click();
        }
    </script>

Code Explanation

  • Here we create a dummy student list.
  • Then it convert to Json string then it store as blob object
  • Finally using anchor tag we download with help of javascript.

Run the application and see the output like below;

json-download-result

Conclusion

Leave behind your valuable queries and suggestions in the comment section below. Also, if you think this article helps you, do not forget to share this with your developer community. Happy Coding 🙂

Jayant Tripathy
Coder, Blogger, YouTuber

A passionate developer keep focus on learning and working on new technology.

Leave a Reply

Your email address will not be published.