15

I am trying to load a local JSONfile of two ways.

This is my json file:

{
  "imgsesion": "fa_closesesion.png",
  "texthome": "volver a la home",
  "logo": "fa_logo.png",
  "menu": {
    "background": "orange",
    "link1": "ESCRITOR",
    "link2": "MÚSICO",
    "link3": "AYUDA ADMIN",
    "submenu": {
      "link1": {
        "text1": "novelas",
        "text2": "obras de teatro"
      },
      "link2": {
        "text1": "compositor",
        "text2": "intérprete"
      }
    }
  }
}
  • Way 1: Using Http

This is my service file (general.service.ts)

  getContentJSON() {
    return this.http.get('assets/json/general.json')
    .map(response => response.json());
  }

This way working ok, but shows the next error in the web browser console:

ERROR TypeError: Cannot read property 'menu' of undefined
  • Way 2: Using HttpClient

This is my service file (general.service.ts)

  getContentJSON() {
    return this.httpClient.get("assets/json/general.json");
  }

It does not work because I can not find the general.json file, it goes through the control of the error and it gives me an error 404

This is the component file (app.component.ts)

export class AppComponent implements OnInit {
  contentGeneral: any;

ngOnInit() {
this.getContentJSON();
}

  getContentJSON() {
    this.generalService.getContentJSON().subscribe(data => {
      this.contentGeneral = data;
    }, // Bind to view
    err => {
      // Log errors if any
      console.log('error: ', err);
    });
  }

}

This is the template file (app.component.html):

<a href="#" routerLink="/home" class="linkHome">{{contentGeneral.texthome}}</a>

<div class="submenu" *ngIf="linkWrite.isActive || isSubMenuWriter">
    <span class="d-block text-right small">{{contentGeneral.menu.submenu.link1.text1}}</span>
    <span class="d-block text-right small">{{contentGeneral.menu.submenu.link1.text2}}</span>
</div>

This is my actual error:

In app.component.ts, I add the import:

import * as data_json from './assets/json/general.json';

But when I launch ng serve it gives me the following error:

enter image description here

How I could resolve it?

Eladerezador
  • 1,277
  • 7
  • 25
  • 48
  • There is another way to do it. You may create an exported json inside a .ts file and import it to your component. Then you may to access to thet json in your component – Sh. Pavel Jun 19 '18 at 09:30

9 Answers9

29

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/))

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Kamil Naja
  • 6,267
  • 6
  • 33
  • 47
16

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));
Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
8

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,
  ...
},
Aravinda Meewalaarachchi
  • 2,551
  • 1
  • 27
  • 24
4

See this article:

import data  from './data.json';
export class AppComponent  {
    json:any = data;
}
Ole
  • 41,793
  • 59
  • 191
  • 359
2

you can use the following code snippet:

declare const require;
const locale = localStorage.getItem('locale');
require(`./file.${locale}.json`)
FrankS101
  • 2,112
  • 6
  • 26
  • 40
1

This happens because you are requesting a JSON file asynchronously, you can handle with safe navigation operator or using ngIf,

<div class="submenu" *ngIf="linkWrite.isActive || isSubMenuWriter">
                  <span class="d-block text-right small">{{contentGeneral?.menu?.submenu?.link1?.text1}}</span>
                  <span class="d-block text-right small">{{contentGeneral?.menu?.submenu?.link1?.text2}}</span>
                </div>

or simply import the JSON file in your component and assign sampleJSON.

import "sampleJSON" from "./sampleJSON"
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Step 1: Open tsconfig.json add following lines in compilerOptions:

"resolveJsonModule": true,
"esModuleInterop": true

Step 2: import json using following code:

import homeData from './data.json';

Note: This code is tested with Angular 9

Yuvraj Patil
  • 7,944
  • 5
  • 56
  • 56
0

Updated answer - Angular 5 Service to read local .json file

In tsconfig.json

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

enter image description here

Surya R Praveen
  • 3,393
  • 1
  • 24
  • 25
0

Create .ts file then copy contents of your json file there and add

export const <objectName> =

something like this

export const faceProfilesSample =
[
{
  "id": 1,
  "depth": 0,
  "burden": null
},
{
  "id": 1,
  "depth": 1.97,
  "burden": 8.58
},

then you can access it by using objectName with import statement like this

import { faceProfilesSample } from "@app/model/face-profiles-sample";

No tsconfig.json changes needed

Pavel Popov
  • 111
  • 1
  • 3