by Sai gowtham

Reading a JSON file in Angular Quickly

In this tutorial, we are going to learn about how to read a (local) json file in angular with the help of an example.

Consider, we have this users.json file in our angular app.

users.json
[
  {
    "id": 23,
    "name": "Opera"
  },
  {
    "id": 24,
    "name": "Kevin"
  },
  {
    "id": 25,
    "name": "Lora"
  }
]

Reading the JSON file

  1. First, open the tsconfig.json file and add the following configuration to the compilerOptions object.
 "resolveJsonModule": true,
  1. Now, import the json file inside your angular component just like how we import other modules.
app.component.ts
import { Component } from '@angular/core';
import * as usersData from '../users.json';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  users: any = usersData;
  constructor() {
    console.log(this.users.default);  }
}

In the above code, we first imported everything * as usersData from the ../users.json file.

Then we accessed the usersData inside the AppComponent by assigning it to the users property.

In the constructor() method, we are logging the data into a browser console.

Note: Angular resolves the JSON file and converts it as a JavaScript object, where default property is holding the data.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course