How to convert json to/from an object in angular|Typescript

Angular is a front-end MVC framework that communicates with the server using the JSON format and uses TypeScript as its programming language.

TypeScript is a superset of JavaScript with additional features for type safety.

In various scenarios, you may find the need to send or consume JSON objects from an Angular application to or from a REST API, requiring the conversion between objects and JSON.

This post explores different methods to convert JSON to an object or an object to JSON in Angular.

It’s worth noting that this topic is commonly addressed in interviews for Angular/TypeScript-based positions.

How to Convert/parse JSON to/from a javascript object in an Angular application

In Applications, REST API is consumed in Angular applications using the HTTP library, The data comes in the format of JSON. Then How do you convert JSON to an object?

There are many ways we can parse JSON to/from a javascript object.

JSON is an inbuilt object in the javascript language

There are two methods in JSON objects

  • JSON.stringify() method string version of an object, which is the conversion of an object to JSON string
  • JSON.parse() - parse string JSON object and creates javascript object
import { Component, OnInit } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
  name = "Angular";
  stringJson: any;
  stringObject: any;
  courseList = [
    {
      courseid: "1",
      coursename: "Java programming",
      author: "Franc",
    },
    {
      courseid: "2",
      coursename: "Learn Typescript programming",
      author: "John",
    },
  ];

  ngOnInit() {
    // Convert String object to JSON
    this.stringJson = JSON.stringify(this.courseList);
    console.log("String json object :", this.stringJson);
    console.log("Type :", typeof this.stringJson);

    // ConvertjSON to an object
    this.stringObject = JSON.parse(this.stringJson);
    console.log("JSON object -", this.stringObject);
  }
}

Here is an HTML code for displaying the output in the browser

<p>Convert jsOn to/from Object Example</p>

<table>
  <tr *ngFor="let item of stringObject">
    <td>{{item.courseid}}</td>
    <td>{{item.coursename}}</td>
    <td>{{item.author}}</td>
  </tr>
</table>

The output you see in the browser and console.

Angular javascript json to object example

Parse/mapping JSON object as Typescript object in angular

create a typescript interface that declares all the fields of JSON objects

Course interface is created for the above json object.

export interface Course {
  couseid: string;
  coursename: string;
  author: string;
}

Next, the parse Course JSON object using the JSON.parse() method returns a generic object of type any. Cast the generic object to an object of the type course.

It will not work in javascript. As we are converting generic to interface using typing feature in typescript.

The advantage of this approach is to avoid runtime errors as most of the type checking happens at compile time only.

let jsonObject: any = JSON.parse(course);
let course: Course = <Course>jsonObj;

parse Javascript object as json using json pInputText

In angular components, if you want to display the javascript object as in JSON prettier printed format. JSON pipe is used.

JSON pipe is an angular inbuilt pipe.

In the HTML template of components, provide the following line of code

{{stringObject | json }}

and output displayed is in the JSON format printed in the browser.

It helps the developer print JSON objects during debugging for any issues.