Angular - Displaying JSON Data



We are currently living in a tech-driven era that generates a huge amount of data that needs to be stored and transferred between systems. It makes sense to have a universal data format that is easy for machines to parse and generate, regardless of the programming language being used. That's when JSON was introduced around 2006 to solve this problem.

What is JSON?

The JavaScript Object Notation, in short JSON, is a lightweight and language independent text-based data format used to store and exchange data. JSON is made up of two main structures:

  • Objects: These are collections of key-value pairs. Each key is a string, and each value can be any data type, such as string, number, etc.

  • Arrays: These are ordered lists of values, which can be objects or other types of data.

All modern programming languages support the above mentioned structures. Hence, we can say JSON is a universal data format.

A simple example of JSON is −

"users": [
   {
     "id": 0121, 
     "name": "Ansh",
     "designation": "Technical Writer",
     "city": "Hyderabad"
   }
]

Here, "id", "name", "designation", and "city" are the keys. And, "0121", "Ansh", "Technical Writer", and "Hyderabad" are their values.

Features of JSON

Here are some important features of JSON:

  • JSON is written in a simple format that is easy for humans to read and understand.
  • Nowadays, many databases are using JSON to store and exchange data.
  • Although JSON is based on JavaScript, it is supported by almost all programming languages. Many languages provide libraries to parse and create JSON data with ease.
  • The data types supported by JSON are similar to what most programming languages have, such as Objects, Arrays, Strings, Boolean, Null and Numbers.
  • JSON provides secure data transfer as well with the help of JWS (JSON Web Signatures).

Displaying JSON data in Angular

There are two ways in which we can display JSON in Angular, which are:

  • By importing the JSON data directly
  • Using HttpClient in services

Before using these approaches to display JSON data, create an angular application and inside this application create a data.json file under assets folder and add some data to it. You can use any name for this file, but the extension should be .json. We are using the following json data −

{
   "users": [
      {
         "name": "Ansh",
         "city": "Hyderabad"
      }
   ]
}

By Importing JSON Data directly

Components are the basic building blocks of an Angular application. They are used to generate a section of web page called View. We can display the JSON data within the view by importing it into the component itself using the import keyword as shown below −

import * as data from '../assets/data.json';

Example

In this example, we are going to display JSON data by importing it into the component. Add the following code in your project's app.component.ts file −

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import * as data from '../assets/data.json';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'display json data';
  // creating an array to store user's data
  userInfo: any[] = data.users; 
}

Now, open app.component.html and add the below code to display the user's data −

<div *ngFor="let item of userInfo">
  <p>Name: {{ item.name }}</p>
  <p>City: {{ item.city }}</p>
</div>

When you run the code, it will display the following result −

display json data in angular

Using HttpClient in Services

Services are TypeScript classes that are used to share data or a common feature across different parts of your angular application. Using a service, it is possible to fetch and display JSON data in your angular application.

Before moving further, let's set up the JSON server for your project. Open CLI and type the following command −

npm install json-server

Now, move to src/assets folder using the cd command. And, use the following command to start the json server −

npx json-server --watch data.json

The JSON server will start on localhost:3000.

Example

This example will explain how to display JSON data using services in angular.

Step 1: Create a service using the following command −

 ng generate service Services/getdata

The above command will create a getdata service in a Services folder.

Step 2: Add the following code in your service file −

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class GetdataService {
  private url = "http://localhost:3000/users";
  constructor(private http: HttpClient) { }
  getData(){
    return this.http.get(this.url); 
  }
}

Step 3: Update the app.component.ts file with the below code −

import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';
import { GetdataService } from './Services/getdata.service';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent implements OnInit {
  title = 'display json data';
  // creating an array to store user's data
  userInfo: any; 
  // injecting the service
  constructor(private getdataService: GetdataService) {}
  ngOnInit() {
    this.getdataService.getData().subscribe((info) => {
      this.userInfo = info; 
    });
  }
}

Step 4: Code of the app.component.html file should be the same −

<div *ngFor="let item of userInfo">
  <p>Name: {{ item.name }}</p>
  <p>City: {{ item.city }}</p>
</div>

Step 5: Before running the code, add the provideHttpClient() inside the providers array of app.config.ts file. −

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';
import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient()]
};

On running, you will get the following output −

display json data in angular
Advertisements