Runninghill Software Development | Downloading Objects as JSON Files in Angular Apps (2024)

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.requestDatathis.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>
Runninghill Software Development | Downloading Objects as JSON Files in Angular Apps (1)

Clicking on the download button will trigger the download

Runninghill Software Development | Downloading Objects as JSON Files in Angular Apps (2)

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

Runninghill Software Development | Downloading Objects as JSON Files in Angular Apps (3)

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

Runninghill Software Development | Downloading Objects as JSON Files in Angular Apps (2024)
Top Articles
Bitcoin’s black swan event: How the return of Satoshi could pose a $75 billion threat
We Work Remotely. Top 100 Remote Companies Hiring.
Creepshotorg
This website is unavailable in your location. – WSB-TV Channel 2 - Atlanta
Access-A-Ride – ACCESS NYC
What happened to Lori Petty? What is she doing today? Wiki
The 10 Best Restaurants In Freiburg Germany
Miss Carramello
A Fashion Lover's Guide To Copenhagen
Pwc Transparency Report
Mens Standard 7 Inch Printed Chappy Swim Trunks, Sardines Peachy
Tcgplayer Store
Michigan cannot fire coach Sherrone Moore for cause for known NCAA violations in sign-stealing case
Trac Cbna
How do I get into solitude sewers Restoring Order? - Gamers Wiki
Morristown Daily Record Obituary
Google Doodle Baseball 76
Acts 16 Nkjv
Promiseb Discontinued
Robeson County Mugshots 2022
U Of Arizona Phonebook
Lakewood Campground Golf Cart Rental
Somewhere In Queens Showtimes Near The Maple Theater
Panolian Batesville Ms Obituaries 2022
Amazing Lash Studio Casa Linda
Like Some Annoyed Drivers Wsj Crossword
PCM.daily - Discussion Forum: Classique du Grand Duché
Weve Got You Surrounded Meme
Boise Craigslist Cars And Trucks - By Owner
Watertown Ford Quick Lane
Truvy Back Office Login
2015 Kia Soul Serpentine Belt Diagram
Wonder Film Wiki
Imagetrend Elite Delaware
The Posturepedic Difference | Sealy New Zealand
Transformers Movie Wiki
Solve 100000div3= | Microsoft Math Solver
The 50 Best Albums of 2023
The best Verizon phones for 2024
Scottsboro Daily Sentinel Obituaries
19 Best Seafood Restaurants in San Antonio - The Texas Tasty
Ticket To Paradise Showtimes Near Marshall 6 Theatre
Craigs List Hartford
Sand Castle Parents Guide
Florida Lottery Claim Appointment
Thotsbook Com
Deezy Jamaican Food
The Sports Academy - 101 Glenwest Drive, Glen Carbon, Illinois 62034 - Guide
Waco.craigslist
Maurices Thanks Crossword Clue
Noaa Duluth Mn
Latest Posts
Article information

Author: Mrs. Angelic Larkin

Last Updated:

Views: 6711

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mrs. Angelic Larkin

Birthday: 1992-06-28

Address: Apt. 413 8275 Mueller Overpass, South Magnolia, IA 99527-6023

Phone: +6824704719725

Job: District Real-Estate Facilitator

Hobby: Letterboxing, Vacation, Poi, Homebrewing, Mountain biking, Slacklining, Cabaret

Introduction: My name is Mrs. Angelic Larkin, I am a cute, charming, funny, determined, inexpensive, joyous, cheerful person who loves writing and wants to share my knowledge and understanding with you.