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.
[
{
"id": 23,
"name": "Opera"
},
{
"id": 24,
"name": "Kevin"
},
{
"id": 25,
"name": "Lora"
}
]Reading the JSON file
- First, open the
tsconfig.jsonfile and add the following configuration to thecompilerOptionsobject.
"resolveJsonModule": true,- Now, import the
jsonfile inside your angular component just like how we import other modules.
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
defaultproperty is holding the data.


