Importing JSON with Angular | Task

Ole Ersoy
Feb - 18  -  1 min

Scenario

The component src/app/app.component.ts wants to import src/app/data.json.

Approach

Configuration

Within tsconfig.json under compilerOptions set resolveJsonModule to true.

In Angular 10+ the compilerOptions are located in tsconfig.app.json.

Note that Angular automatically parses the JSON for us, so we do not need to do JSON.parse(...).

import * as data from './data.json';
export class AppComponent  {
    json:any = data;
    constructor() {
        console.log(json.default)
    }
}

The default property on the imported data json module contains the data.

Demo

In this Angular 15 demo geo.json is imported like this:

import data from './geo.json';