Angular 10 (import JSON)

VANDANA GUPTA
2 min readJan 30, 2021

Photo by Ferenc Almasi on Unsplash

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>
In browser

You can show it in the console in app.component.ts

constructor()
{
console.log(`Id:${result.id}. Name:${result.name}. Class:${result.class} `)
}
In Browser’s console

Thank you ✨✨

Happy coding !!

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

VANDANA GUPTA
VANDANA GUPTA

Written by VANDANA GUPTA

An inquisitive person. A learner.

Responses (1)

Write a response