Downloading Objects as JSON files in Angular

In our Angular applications , we often create rich data objects that give us insight into how our application is behaving. Whether we’re creating complex state management objects , error logs or diagnostics ,what if you wanted to export this data for further analysis or for users to download?

In this blog post, we’ll explore how to download a session storage object as a JSON file in an Angular application. This feature can be particularly useful when you want to provide users with the ability to backup or export their session-related data.

Prerequisites

Before we dive into the implementation, make sure you have the following prerequisites:

  • Basic knowledge of Angular and TypeScript.
  • An Angular project set up and ready to work with.

Implementation Steps

We’ll break down the implementation into the following steps:

  1. Retrieve session storage data: Fetch the data from session storage that you want to export as a JSON file.
  2. Convert to JSON: Convert the retrieved data to a JSON string.
  3. Create a download function : Implement a function to trigger the download
  4. Trigger the download: Create a button in the user interface that, when clicked, triggers the download of the JSON file.

Let’s get started!

Retrieve Session Storage Data

In previous blogs I’ve outlined how to create a generic session storage service as well as how to use that service to store ,process and view network logs.

Angular HTTP Interceptors: creating a custom http diagnostics report

Using the project I created there as a base , I can download the network logs I created from session storage as a JSON file and be able to use the insights and diagnostics I created to make meaningful decisions regarding how to optimise the network requests my application is making.

Note: For the rest of the blog I will be referencing code that can be found in this repo , so if you want to see the full implementation please clone and follow along

GitHub – Yashlin-Naidoo/BaseUi.Angular at feature/downloadStorage

In that project , in the SessionStorageService , I created a method for retrieving and processing the network information I had stored in the browser session storage.

retrieveRequestObjectFromStorage() {
    const resData = this.getItem(RESPONSE_ARRAY_KEY)
    const reqData: RequestArray[] = this.getItem(REQUEST_ARRAY_KEY)
    const requestData = this.reduceAndCountRequests(reqData)
    const responseData = this.reduceAndCountRequests(resData)
    return { requestData, responseData }
  }

So my first portion is done , I can now go to the app.component.ts of that angular app and I will see that I have already written code to extract that data , store it in variables and display it on the page

const sessionObject = this.sessionStorageService.retrieveRequestObjectFromStorage();
this.requestArray = sessionObject.requestData
this.responseArray = sessionObject.responseData

Convert to JSON

Now that I have the data , I need to convert it to a JSON blob , this will allow me to download it from the Application to my device as a JSON file

convertToJsonFile(){
    const sessionObject = this.sessionStorageService.retrieveRequestObjectFromStorage();
    const jsonString = JSON.stringify(sessionObject);
    const blob = new Blob([jsonString], { type: 'application/json' });
    return blob;
   }

Lets break down this code

  1. Convert to JSON String: const jsonString = JSON.stringify(sessionObject); After retrieving the data, it is converted to a JSON-formatted string using JSON.stringify(). This step serializes the JavaScript object (sessionObject) into a string that represents the same data in JSON format.
  2. Create a Blob: const blob = new Blob([jsonString], { type: 'application/json' }); This line creates a Blob object from the JSON string. A Blob is a binary large object that can store data of various types, in this case, JSON data. The second argument to the Blob constructor specifies the MIME type of the data. Here, it’s set to 'application/json', indicating that the data is in JSON format. This helps browsers understand how to handle the Blob.

Create a download function

convertToJsonFile(){
    const sessionObject = this.sessionStorageService.retrieveRequestObjectFromStorage();
    const jsonString = JSON.stringify(sessionObject);
    const blob = new Blob([jsonString], { type: 'application/json' });
    return blob;
   }

   downloadRequestObject(){
    const blob = this.convertToJsonFile();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'network_calls.json';
    a.click();
    window.URL.revokeObjectURL(url);
  }
  1. Create Blob: This function starts by calling the convertToJsonFile() function to obtain the JSON data as a Blob. The convertToJsonFile() function returns the Blob containing the JSON data.
  2. Create a URL: window.URL.createObjectURL(blob) generates a URL that represents the Blob data. This URL is stored in the url variable.
  3. Create an Anchor Element: An <a> element is created using document.createElement('a'). This element will act as the download link for the JSON file.
  4. Set Anchor Element Properties: Several properties of the <a> element are configured:
    • href: The href attribute is set to the generated URL (url) from the Blob, effectively linking the anchor to the Blob data.
    • download: The download attribute is set to ‘network_calls.json’, specifying the default file name when the user initiates the download.
  5. Trigger Click: The <a> element is programmatically clicked using the a.click() method. This simulates a user clicking the link, which prompts the browser to download the JSON file.
  6. Revoke URL: After the download is initiated, window.URL.revokeObjectURL(url) is called to release the resources associated with the generated URL, ensuring efficient memory usage.

In summary, the convertToJsonFile() function prepares the data as a Blob, and the downloadRequestObject() function creates a download link, triggers the download, and cleans up the generated URL.

Trigger the download

The simplest step , lets add a button to our html to trigger the download function we have just created

<!-- app.component.html -->
<button type="button" (click)="downloadRequestObject()">Download Network Data</button>

Clicking on the download button will trigger the download

And then we can view our JSON file with all our nicely processed network data

Conclusion

This functionality allows users and developers to export and analyze data from your Angular application conveniently. It’s a valuable feature when dealing with diagnostic data, error logs, or any other data that users or developers may want to review or share.

Reminder: If you want to see this code in action , you can clone and run the repo here

https://github.com/Yashlin-Naidoo/BaseUi.Angular/tree/feature/downloadStorage

12 Comments

  1. It’s amazing to visit this web page and reading the views of all friends regarding
    this paragraph, while I am also eager of getting
    familiarity.

  2. This design is spectacular! You most certainly know how to keep a reader amused.
    Between your wit and your videos, I was almost moved to start my own blog (well,
    almost…HaHa!) Excellent job. I really enjoyed what you had to say, and more than that, how you presented it.

    Too cool!

  3. Hi there, I discovered your site by means
    of Google whilst searching for a similar matter, your website got here up, it seems
    good. I’ve bookmarked it in my google bookmarks.
    Hi there, just changed into alert to your blog thru Google, and
    located that it is really informative. I am gonna be careful for brussels.
    I’ll appreciate if you proceed this in future. Many other people shall be benefited out of your writing.
    Cheers!

  4. casino online

    I’m not sure exactly why but this weblog is loading extremely slow for me.
    Is anyone else having this issue or is it a issue on my end?
    I’ll check back later on and see if the problem still exists.

  5. Heya i’m for the first tіme here. I found this board
    and I in finding It truly useful & it helped mе out mucһ.
    I am hoping to offer one thing again and aid others such as you aided me.

  6. Hurrah! After all I got a web site from where I be able
    to genuinely obtain useful facts regarding my study and knowledge.

  7. I’m gone to tell my little brother, that he should
    also go to see this website on regular basis to take updated
    from most up-to-date reports.

  8. I was able to find good advice from your blog posts.

  9. I am sure this piece of writing has touched all the internet people, its really really fastidious post on building
    up new web site.

  10. Hi there! Do you know if they make any plugins to protect against hackers?
    I’m kinda paranoid about losing everything I’ve
    worked hard on. Any suggestions?

  11. It’s difficult to find experienced people for this subject, however,
    you sound like you know what you’re talking about!
    Thanks

  12. mozellealdrich

    Hola! I’ve been reading your website for a long time now and finally got the courage to
    go ahead and give you a shout out from Atascocita
    Texas! Just wanted to say keep up the great job!

Leave a Comment

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