Sometimes you would need to import local JSON file into your Angular application and use the data. In this example we will show you how to include and compile JSON object into your app, which means we will not make extra HTTP request to include it.

 

OK, so in order to achieve this - we have to create file with the name: json-typings.d.ts and save it in app folder. This file will have just couple of lines:

                    declare module "*.json" {
  const value: any;
  export default value;
}
                  

And now, in your component, you can include your .json file by simple import request:

                    import * as dataObject from "../../assets/my_custom_file.json";
...
console.log(dataObject);

                  

 

And that is it, plain and simple.

 

Another example would be to make HTTP request and load this JSON file as object. If this is going to happen on page which should be indexed in Google - we do not recommend this approach, because it will send additional (but not needed) request which will affect your Google page speed performance and in the end it can affect the position on Google search results.

But if you still need it, here it is:

                    import { HttpClient} from '@angular/common/http';
//...
data: any = {};
//...
const filePath = 'assets/my_custom_file.json';
this.http.get<{}>(filePath).subscribe(
            data => {
              this.data = Object.assign({}, translation || {});
              console.log(this.data)
            },
            error => {
              this.data = {};
            }
          );