Create Angular Project
Open command prompt, go to the folder (C:/ or D:/) where you want to create your project. Type this command to create a project.
ng new json2angular
Open NotePad and save the file with name sales-data.json (or any name you wish). You must save the file inside the assets folder in your project.
/src/assets/sales-data.json
Note that, any file that is saved in the assets folder can easily be accessed in your Angular projects.
Now "add some data" in the JSON file. For example,
[ { "Month": "Jan", "Sales_Figure": 21, "Perc": 5 }, { "Month": "Feb", "Sales_Figure": 32, "Perc": 15 }, { "Month": "Mar", "Sales_Figure": 19, "Perc": 11 } ]
Let’s see how we can read and extract data from this Local JSON file that we have just created.
1st Method: Using Angular HttpClient to read JSON file
Follow these steps.
• Import HttpClientModule to the project - Open app.module.ts file and add HttpClientModule
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
• Import HttpClient service – Now, we’ll create acomponent by importing the HttpClient class (to perform Http requests) to our project.
import { Component} from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { constructor (private httpService: HttpClient) { } arr: any = []; ngOnInit () { this.httpService.get('./assets/sales-data.json').subscribe({ next: data => { this.arr = data as string []; // populate array with data. console.log(this.arr); // show data in console window. }, error: HttpErrorResponse => { console.log(HttpErrorResponse.message); // show error message, if any. } }) } }
Run the application.
ng serve –o
I have not created any template to show the data. However, you will see the output in the browser’s console window. 👇
Now, let’s understand the methods.
First, we’ll create an HTTP service, so we can have access to the methods and properties provided in the HttpClient class.
constructor (private httpService: HttpClient) { }
The get() method has the URL of the file as a parameter. I am making an HTTP request here to get the data.
Next we’ll subscribe to the information that we’ll receive through the request. The subscribe() method is used to execute an Observable (the source of the information). This method has two properties (or notifications), next and error.
Note: in previous versions like Angular 6, the process was slightly different.
this.httpService.get('./assets/sales-data.json').subscribe( data => { this.arr = data as string []; // populate array with data. console.log(this.arr); }, (err: HttpErrorResponse) => { console.log (err.message); } );
Although the above code will also work in Angular 15, the subscribe() method will have Strikethrough, an indication that the method is deprecated.
2nd Method: Using "import" statement in TypeScript 2.9+
This is a very simple method. All you have to do is just import the JSON file in your Angular application and extract the data from the file.
Follow these steps.
• Open app.components.ts and write the below code in it.
import { Component} from '@angular/core'; import * as salesData from '../assets/sales-data.json'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { title = 'Read data from JSON file in Angular 15'; sales: any = (salesData as any).default; ngOnInit () { // console.log(salesData); } }
This method of data extraction from a file is very straightforward. The JSON data is stored in a variable named sales. We can now extract and display the data in our template using an HTML table.
• Create template – Open app.component.htm file and write the below markup into it.
<!DOCTYPE html> <style> * { font-family: Calibri; } </style> <h2>{{title}}</h2> <div> <p>Monthly sales figues</p> <table *ngIf="sales"> <!-- ADD HEADERS --> <tr> <th>Month</th> <th>Percentage</th> <th>Figures</th> </tr> <!-- BIND ARRAY TO TABLE --> <tr *ngFor="let sd of sales"> <td>{{sd.Month}}</td> <td>{{sd.Perc}}</td> <td>{{sd.Sales_Figure}}</td> </tr> </table> </div>
That’s it. Run the project.
ng serve –o
Result 👇