3+ Ways for Reading Local JSON Files with Angular 15

3+ Ways for Reading Local JSON Files with Angular 15

In this post, we'll show you three different methods to read local JSON files in your Angular 15 application, each with an example:

  • Reading Local JSON Files Using TypeScript 2.9+ import Statement,
  • Reading Local JSON Files Using Angular HttpClient,
  • Reading Local JSON Files in Offline Angular Apps Using ES6+ import Statement

JSON is used by Angular in a variety of contexts, including configuration. For example, the project generated by Angular CLI comprises many files with the .json extension, most notably the package.json and angular.json files.

The package.json file is needed by Node and NPM to setup the project and install packages, while the angular.json file is used to store all of the angular project's settings. It offers workspace-wide and project-specific setup settings.

These JSON files are handled automatically by Node and Angular CLI, but you may also create and read JSON files in your Angular applications remotely from URLs or locally from the assets folder for example.

Read JSON files from the assets folder

Anything you place in the assets folder in the Angular app will be accessible in the browser by default, and you may even add your own folder other than assets. When you scaffold an Angular App using the Angular CLI, the project structure contains assets folder that you can use to put files including JSON files.

Whatever you place in the assets folder is publicly accessible and can be read with an HttpClient. Next, we'll see an example of how to read a JSON data file from the assets folder using Angular HttpClient.

Let's have a look at some of these methods in action.

JSON and Angular

JSON is an acronym for JavaScript Object Notation, which refers to a notation that uses JavaScript objects. Since Angular is Javascript framework, it makes extensive use of JSON especially for configuration. In this post, we will learn how to read Angular JSON files.

In addition to JavaScript and TypeScript, JSON strings are supported by almost all other programming languages. As a consequence, JSON is an effective format for exchanging data between different languages and platforms (server and client). This article will show you how to utilize JSON in the context of Angular 15.

JSON is far smaller and more adaptable than XML, as well as being easier to grasp. JavaScript objects are the foundation of JSON, which is a language-agnostic data transport standard that can convey data between any computer systems.

Reading Local JSON Files Using TypeScript 2.9+ import Statement

Angular 6.1+ supports TypeScript 2.9 which allows you to use the import statement to import local JSON files just like any TypeScript module. To enable this feature, you need to add and set the resolveJsonModule option to true in the tsconfig.json file under the compilerOptions key file. This is an example:

import { Component, OnInit } from '@angular/core';
import * as data from './data.json';

@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular 15 JSON Example';

  products: any = (data as any).default;

  constructor(){}
  ngOnInit(){
    console.log(data);
  }
}

We use the ngOnInit() life-cycle method of Angular OnInit interface to display the imported JSON file in the console.

This is a screenshot of the imported JSON file in the console:

Import JSON in Angular and TypeScript

This assumes, you have a data.json file in the src/app folder of your project with the following values:

[
    {
        "id": 1,
        "name": "Licensed Frozen Hat",
        "description": "Incidunt et magni est ut.",
        "price": "170.00",
        "imageUrl": "https://source.unsplash.com/1600x900/?product",
        "quantity": 56840
    },
    {
        "id": 2,
        "name": "Rustic Concrete Chicken",
        "description": "Sint libero mollitia.",
        "price": "302.00",
        "imageUrl": "https://source.unsplash.com/1600x900/?product",
        "quantity": 9358
    },
    {
        "id": 3,
        "name": "Fantastic Metal Computer",
        "description": "In consequuntur cupiditate et unde minus.",
        "price": "279.00",
        "imageUrl": "https://source.unsplash.com/1600x900/?product",
        "quantity": 90316
    }
]

Please note that this supported only in Angular 6.1+ versions.

Reading Local JSON Files Using Angular HttpClient

The second method that you can use to import JSON files in your Angular application is Angular HttpClient. Let's see this by example.

The HTTP protocol is utilized by the majority of front-end apps to connect with the server. When working with an application that uses Angular 15, we may make use of the HttpClient service available from the @angular/common/http package to read JSON files from an Angular application. In this section, we'll look at how to fetch JSON files using RxJS Observables.

First, you need to import HttpClientModule in your app. Open the src/app/app.module.ts file and update it as follows:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    AboutComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Next, move the previous src/app/data.json file to the src/assets folder.

Next, open the src/app/app.component.ts file, import and inject HttpClient as follows:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";


@Component({
  selector: 'app-root',
  template: `<ul>
      <li *ngFor="let product of products">

      </li>
  </ul>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'Angular 15 JSON Example';
  products: any = [];

  constructor(private httpClient: HttpClient){}
  ngOnInit(){
    this.httpClient.get("assets/data.json").subscribe(data =>{
      console.log(data);
      this.products = data;
    })
  }
}

Here we used HttpClient to read the data.json file from the assets folder of our Angular 15 project.

Reading Local JSON Files in Offline Angular Apps Using ES6+ import Statement

If your Angular application goes offline, reading the JSON file with HttpClient will fail. In this case, we have one more method to import local JSON files using the ES6+ import statement which supports importing JSON files.

But first we need to add a typing file as follows:

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

Add this inside a new file json-typings.d.ts file in the src/app folder.

Now, you can import JSON files just like TypeScript 2.9+.

import * as data from "data.json";

Using Angular JSON Pipe

Angular provides a built-in JSON pipe that can be used to create a JSON representation of a given data value. This pipe takes no arguments and uses the browser's JSON.stringify function to build the JSON string. A JavaScript object may be converted to a JSON string using this method.

The JSON pipe can be used as follows:


Read JSON files with Fetch

To read JSON files, we may also make use of the native Fetch API, which is built into all current browsers.

The Fetch API offers a more robust and versatile set of features for obtaining resources locally or via the network including JSON files.

This is an example Angular 15 component that uses the Fetch API to read a JSON file:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'Read JSON File with Angular 15';
  productsArray: any;

  constructor() { }

  ngOnInit(): void {
    fetch('./assets/products.json').then(res => res.json())
    .then(jsonData => {
      this.productsArray = jsonData;
    });
  }
}

This is similar to how we read JSON files using Angular HttpClient, except instead of Observables, it uses Promises.

Conclusion

A developer's workflow may benefit from the ability to import JSON files and process them, making it easier and more efficient to create new applications. In addition to a broad variety of configuration options, it allows for the capture of data locally for development purposes. We've seen 3+ techniques for importing and reading local JSON files in Angular 15 and TypeScript in this tutorial.



✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

✋ Want to master Angular 14? Read our angular tutorial and join our #DailyAngularChallenge where we learn to build components, directives, services, pipes and complete web, mobile, and desktop applications with latest Angular version.

✋ Make sure to join our Angular 14 Dev Community 👈 to discuss anything related to Angular development.

❤️ Like our page and subscribe to our feed for updates!

Find a list of emojis to copy and paste