Angular 6 - Load JSON from local

By this way...

import "file" from "./file.json" 

I got red line and got error like module not found by angular.

After some RND I got another way which works for me. Hope it may help someone.

var data = require('src/file.json');
console.log("Json data : ", JSON.stringify(data));

The simplest solution:

import "myJSON" from "./myJson"

Important update!

I found, that this method stops working in newest Angular versions, because of this error:

ERROR in src/app/app.weather.service.ts(2,25): error TS2732: Cannot find module './data.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

To make it works, go to the tsconfig.json and add this two, inside

compilerOptions( tsconfig.json ) :

"resolveJsonModule": true,
"esModuleInterop": true,

After change, re-run ng serve.

If you only use the first option, you can get an error like this:

ERROR in src/app/app.weather.service.ts(2,8): error TS1192: Module '"....app/data/data.json"' has no default export.

(I found this very good answer here (https://www.angularjswiki.com/angular/how-to-read-local-json-files-in-angular/))


For the Angular 2, Angular 4 and Angular 5, you can use following method to load your local .json files to the component.

const data = require('../../data.json');

export class AppComponent  {
    json:any = data;
}

To use require with in your component, you needed to install @types/node by running

npm install @types/node --save-dev

Do the following configuration change under tsconfig.app.json > compilerOptions

"compilerOptions": {
  "types": ["node"],
  ...
},

After Angular 6, you can use direct imports form file system as follows.

import data  from '../../data.json';

export class AppComponent  {
    json:any = data;
}

Do the following configuration change under tsconfig.app.json > compilerOptions

"compilerOptions": {
  ...
  "resolveJsonModule": true,
  "allowSyntheticDefaultImports": true,
  "esModuleInterop": true,
  ...
},

Tags:

Json

Angular