Angular 10 (import JSON)
Angular 10 is based on Typescript version 3.9. We will configure the tsconfig.app.json file as this file provides the options used when working with code in the app folder.
Configuration
We need to add additional compiler options.
- ResolveJSONModule
--resolveJsonModule
include modules imported with .json extension.The type of this option is boolean and by default it's false
- ESModuleInterop
-esModuleInterop
it allows import from modules with no default export. So, it's required as .json file has no default output. The type of this option is false and by default it's false.
After configuring these two options. tsconfig.app.json looks like :
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"resolveJsonModule": true,
"esModuleInterop": true
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
You are done and you can import a .json file with an import statement.
I have made a data.json file under /assets folder:
{
"id":"1",
"name":"John Doe",
"class":"12"
}
Now go to any component and inside the .ts file write an import statement. In my case, I have app.component.ts file:
import result from "../assets/data.json";
You can use the result as you use an object. If you want to use it to render in the browser just assign the result to any variable in app.component.ts file
export class AppComponent {
title = 'first';
Data = result; // result is assigned to Data
}
In app.component.html:
<p>Your id :{{Data.id}} </p>
<p>Your name:{{Data.name}}</p>
<p>Your class:{{Data.class}}</p>

You can show it in the console in app.component.ts
constructor()
{
console.log(`Id:${result.id}. Name:${result.name}. Class:${result.class} `)
}

Thank you ✨✨
Happy coding !!