Read an external JSON file in Angular and Convert Data to HTML Table

← PrevNext →

You can use the HttpClient service in Angular to read and extract data from an external JSON file. Using the Get() method of HttpClient class, you can easily open and read data from a JSON file. Here in this post, I am sharing a simple example on how to read JSON data from a file and convert the data to an HTML table.

Read JSON Data from File and Bind it to an HTML Table in Angular

Hi there, Angular 15 was resently released with some cool new features. I would recommend upgrading to the current version. In Angular 15, you can use two simple methods to read data from JSON file and convert the data into a table. The process is slightly different and its worth exploring.

How to read data from a local JSON file in Angular 15 and convert data to an HTML table

JSON or JavaScript Object Notation, as you know is a data format that allows you to conveniently store and share data using any medium. JSON is language independent and can be easily bind with any kind of application. You can use JSON data in your Angular applications.

Related: How to Bind JSON array or data to an HTML table in AngularJS using ng-repeat

The JSON Data

Here’s a sample JSON. I have saved the data in a file named Birds.json.

[{
    "ID": "001",
   "Name": "Eurasian Collared-Dove",
    "Type": "Dove",
    "Scientific Name": "Streptopelia"
},
{
    "ID": "002",
    "Name": "Bald Eagle",
    "Type": "Hawk",
    "Scientific Name": "Haliaeetus leucocephalus" 
},
{
    "ID": "003",
    "Name": "Cooper's Hawk",
    "Type": "Hawk",
    "Scientific Name": "Accipiter cooperii" 
}]

After you create file, you'll have to save the file inside the assets folder in your angular project. Here’s the path.

/src/assets/birds.json

But first, create the project.

Create the Angular Project

I am hoping that you have already setup Angular in your computer. If not, then please read this post. It will guide you with the setup procedure.

Open cmd prompt and go to the folder where you want to create your project. Type this command …

ng new json2angular

Now, go to the folder.

cd json2angular

Note: Don't forget to save the JSON file in the assets folder inside your angular project.

Import HttpClientModule to the Project

First, open app.module.ts file under src/app/ folder and add HttpClientModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/https';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Next, we’ll create our component, where we’ll add or import HttpClient service. Adding this service to our project will ensure that we have access to the Get() method and its properties, which we need to access files in the server and read its contents.

Open app.component.ts file and add the below code.

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/https';
import { HttpErrorResponse } from '@angular/common/https';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'JSON to Table Example';
  constructor (private httpService: HttpClient) { }
  arrBirds: string [];

  ngOnInit () {
    this.httpService.get('./assets/birds.json').subscribe(
      data => {
        this.arrBirds = data as string [];	 // FILL THE ARRAY WITH DATA.
        //  console.log(this.arrBirds[1]);
      },
      (err: HttpErrorResponse) => {
        console.log (err.message);
      }
    );
  }
}

Now, let's understand what the above code is doing.

I have declared an array named arrBirds of type string. I am adding the JSON data extracted from the file into an array, which I'll later bind with a <table> using *ngFor directive.

You can now launch the server, ng serve --o, to check if there are no errors. Please make sure that you have saved the JSON file Birds.json in the assests folder in your project, else it will throw an error.

Now let’s create our application template. Its where we’ll add the HTML <table> element and bind the array to the table.

Open app.commonent.html file and copy and paste the below markup to the file.

<div style="text-align:left;width:500px;">
    <h1>
        {{ title }}!
    </h1>

    <table *ngIf="arrBirds">
        <!-- ADD HEADERS -->
        <tr>
            <th>ID</th>
                <th>Name of Bird</th>
                    <th>Type of Bird</th>
        </tr>

        <!-- BIND ARRAY TO TABLE -->
        <tr *ngFor="let bird of arrBirds">
            <td>{{bird.ID}}</td>
                <td>{{bird.Name}}</td>
                    <td>{{bird.Type}}</td>
        </tr>
    </table>
</div>

Save the file. Go to the browser to check the output. If you want you can some CSS style to the table and its content.

You can add in-line style to your table or add few classes in your app.component.css file.

table, th, td 
{
    margin: 10px 0;
    border: solid 1px #333;
    padding: 2px 4px;
}
th {
    font-weight:bold;
}

That's how you convert JSON data to an HTML table in Angular. Now you know how simple it is.

🚀 Now, you can also do this easily and more efficiently in Angular's lastest version, using two different methods. Check this out.

I am using Angular HttpClient service in my example, so I can have access to the Get() method, using which I can access any file in the server, read the file and populate the data in an Array. I am then binding the array to an HTML <table> element (you can bind it with other elements like the SELECT element and view it.

Happy coding.

← PreviousNext →