Different ways to read Local JSON file in Angular

There are different ways to read local Json file in Angular. In this example, we’ll see 3 different ways to read local JSON file in Angular with example. We’ll also see how to read and display the data from JSON file in angular.

Different ways to read local JSON file.

  1. Reading JSON file using typescript import statement.
  2. Reading JSON file using Angular HttpClient.
  3. Reading JSON file using ES6+ import statement for offline Angular apps.

Generate project

Create new angular project using the following angular cli command.

ng new angular-read-local-json-file

and then you’ll be asked to choose the stylesheet format, select your preferred format and hit enter.

Create new angular project

Then Angular CLI will create necessary file and folders and will install the necessary npm packages.

Navigate to project directory

cd angular-read-local-json-file

Create Dummy Json Data File

We’ll create dummy json data files which will be containing list of employees.

src/assets/employees.json

{ "employees": [ { "id": "1", "firstName": "Tom", "lastName": "Cruise" }, { "id": "2", "firstName": "Maria", "lastName": "Sharapova" }, { "id": "3", "firstName": "James", "lastName": "Bond" } ] }

Method 1. Import JSON file using typescript import statement

Angular 6.1 released with the support of typescript 2.9. and Typescript 2.9 released with resolveJsonModule

--resolveJsonModule allows for importing, extracting types from and generating .json files.

Now we’ll create a new component which will read json file using import statement.

create new component using the following command:

ng generate component read-json-using-typescript-import

so our component will looks as following:

read-json-using-typescript-import.ts

import { Component, OnInit } from "@angular/core"; import employees from "../../assets/employees.json"; @Component({ selector: "app-read-json-using-typescript-import", templateUrl: "./read-json-using-typescript-import.component.html", styleUrls: ["./read-json-using-typescript-import.component.css"] }) export class ReadJsonUsingTypescriptImportComponent implements OnInit { employeeData: any; constructor() { this.employeeData = employees; } ngOnInit() {} }

In the above code, we’ve imported JSON data using highlighted the second line and we’ve assigned that data to employeeList so that we can access it from the template file.

If you’ll run the above code it’ll throw the following error.

Error in src/app/read-json-using-typescript-import/read-json-using-typescript-import.component.ts (2:26) Cannot find module '../employees.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

This error is indicating that use --resolveJsonModule compiler option that lets us import JSON modules from within TypeScript modules.

Now to add --resolveJsonModule compiler option, we’ll need to add following options tsconfig.json as following

tsconfig.json

{ ... "compilerOptions": { ... "resolveJsonModule": true, "esModuleInterop": true .... } ... }

Now update the following change in template file

read-json-using-typescript-import.component.html

<h2>Read Local JSON file data using typescript import</h2> <table id="employees"> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> </tr> <tr *ngFor="let employee of employeeData.employees"> <td>{{employee.id}}</td> <td>{{employee.firstName}}</td> <td>{{employee.lastName}}</td> </tr> </table>

Update css file as following

#employees { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #employees td, #employees th { border: 1px solid #ddd; padding: 8px; } #employees tr:nth-child(even){background-color: #f2f2f2;} #employees tr:hover {background-color: #ddd;} #employees th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: red; color: #fff; }

Output

Import JSON file using typescript import statement
Import JSON file using typescript import statement

Method 2: Import JSON file using Angular HttpClient.

This method will use angular HttpClient to read local json file. Now let’s see an example of it.

Now generate new component using the following command:

ng generate component read-json-file-using-httpclient

Now we’ll see how can we use Angular HttpClient to read local json file in angular.

We’ll first need to import HttpClientModule in app.module.ts as following

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { ReadJsonUsingTypescriptImportComponent } from './read-json-using-typescript-import/read-json-using-typescript-import.component'; import { ReadJsonFileUsingHttpclientComponent } from './read-json-file-using-httpclient/read-json-file-using-httpclient.component'; @NgModule({ imports: [ BrowserModule, FormsModule ,HttpClientModule], declarations: [ AppComponent, ReadJsonUsingTypescriptImportComponent, ReadJsonFileUsingHttpclientComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }

Update the component with the following changes:

read-json-file-using-httpclient.component.ts

import { Component, OnInit } from '@angular/core'; import { HttpClient,HttpErrorResponse } from "@angular/common/http"; import { Observable, throwError } from 'rxjs'; import { catchError, retry } from 'rxjs/operators'; @Component({ selector: 'app-read-json-file-using-httpclient', templateUrl: './read-json-file-using-httpclient.component.html', styleUrls: ['./read-json-file-using-httpclient.component.css'] }) export class ReadJsonFileUsingHttpclientComponent implements OnInit { employeeData:any; constructor(private httpClient: HttpClient){ } ngOnInit(){ this.httpClient.get<any>("assets/employees.json").subscribe((data)=> this.employeeData = data ) } }

Update template file with the following changes

read-json-file-using-httpclient.component.html

<h2>Read Local JSON file data using HttpClient</h2> <table id="employees"> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> </tr> <tr *ngFor="let employee of employeeData?.employees"> <td>{{employee.id}}</td> <td>{{employee.firstName}}</td> <td>{{employee.lastName}}</td> </tr> </table>

and update your css file with this changes.

#employees { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #employees td, #employees th { border: 1px solid #ddd; padding: 8px; } #employees tr:nth-child(even){background-color: #f2f2f2;} #employees tr:hover {background-color: #ddd;} #employees th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: red; color: #fff; }

If you’ll run this code, you’ll get the following output.

Output

Import JSON file using Angular HttpClient.
Import JSON file using Angular HttpClient.

Method 3: Reading JSON file using ES6+ import statement for offline Angular apps

Angular HttpClient will not work when application goes offline. For offline angular app we have other way to read local json file in angular which is ES6+ import statement

Now we’ll see an example how can we use ES6+ import to read local json file for offline app.

Add typing file src/app/json-typings.d.ts

declare module "*.json" { const value: any; export default value; }

and import json file same as first method.

read-json-file-using-es6.component.ts

import { Component, OnInit } from '@angular/core'; import employees from "../../assets/employees.json"; @Component({ selector: 'app-read-json-file-using-es6', templateUrl: './read-json-file-using-es6.component.html', styleUrls: ['./read-json-file-using-es6.component.css'] }) export class ReadJsonFileUsingEs6Component implements OnInit { employeeData: any; constructor() { this.employeeData = employees; } ngOnInit() { } }

Now update template file as following:

read-json-file-using-es6.component.html

<h2>Read Local JSON file data using ES6+</h2> <table id="employees"> <tr> <th>ID</th> <th>First Name</th> <th>Last Name</th> </tr> <tr *ngFor="let employee of employeeData.employees"> <td>{{employee.id}}</td> <td>{{employee.firstName}}</td> <td>{{employee.lastName}}</td> </tr> </table>

read-json-file-using-es6.component.css

#employees { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #employees td, #employees th { border: 1px solid #ddd; padding: 8px; } #employees tr:nth-child(even){background-color: #f2f2f2;} #employees tr:hover {background-color: #ddd;} #employees th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: red; color: #fff; }

Output

Reading JSON file using ES6+ import statement for offline Angular apps

That’s it for reading local json file in angular. I hope you like this article.


Also Read