Angular 17 Pipe Json examples | pretty format code
- Admin
- Mar 10, 2024
- Typescript Angular Angular-pipes
It is a short tutorial about angular pipe json examples.
- How to print json objects in the Angular component
Angular has an inbuilt pipe called jsonPipe
from @angular/common🔗 module, Used to Convert typescript objects into JSON format type.
It is useful to debug and manipulate object data during development.
Here is the syntax in the HTML template
{{object|json}}
How do you print an object without json pipe in Angular?
Let’s declare an Employee.ts
object in a typescript angular application.
export class Employee {
id: Number;
name: string;
salary: Number;
}
Let’s create an angular typescript component.
Define and Initialize an array of an employee with data.
import { Component } from "@angular/core";
import { Employee } from "./employee";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
employees: Employee[] = [
{ id: 1, name: "Ram", Salary: 5000 },
{ id: 2, name: "John", Salary: 1000 },
{ id: 3, name: "Franc", Salary: 3000 },
{ id: 4, name: "Andrew ", Salary: 8000 },
];
constructor() {}
ngOnInit() {}
}
Let’s print the object array or object in the Angular HTML component.
<div>{{employees}}</div>
Output
[object Object],[object Object],[object Object],[object Object]
An object or array object prints an object in [object object]
format, which is not helpful for a developer to debug the content of an object.
Hence, JSON pipe in Angular helps developers print the content of an object in pretty json format.
Angular JSON pipe Example
This example contains an Array of objects printed in JSON.
Let’s use json pipe for an object or array of objects.
<div>{{employees |json}}</div>
And output
[
{ "id": 1, "name": "Ram", "Salary": 5000 },
{ "id": 2, "name": "John", "Salary": 1000 },
{ "id": 3, "name": "Franc", "Salary": 3000 },
{ "id": 4, "name": "Andrew ", "Salary": 8000 }
]
JSON is displayed as a string format without a delimiter.
How do you print the json in a pretty format?
JSON pipe with Async API
Async Data is an asynchronous data coming from REST API’s. For this example, Create an Async Data using the Of
operator, You can replace it with REST APIs
import { Component } from "@angular/core";
import { Employee } from "./employee";
import { Observable, of } from 'rxjs';
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
data$: Observable<any>;
employees: Employee[] = ;
constructor() {}
ngOnInit() {
this.data$ = of([
{ id: 1, name: "Ram", Salary: 5000 },
{ id: 2, name: "John", Salary: 1000 },
{ id: 3, name: "Franc", Salary: 3000 },
{ id: 4, name: "Andrew ", Salary: 8000 },
]);
}
}
In the example, Declare a variable data$
with the type of Observable. Initialize a variable with data using the Of
operator. Of operator used to convert any object to Observable.
The Html component used the async keyword with the pipe. First, async data is converted to normal data, again transformed into JSOn string.
<div>{{employees | async | json}}</div>
JSON pipe using JSON String
In the example, JSON data is assigned to a string, enclosed in a single quote. It is a String object, You can print the String object using {{str}}
A variable declared is a string type, not an object.
you can still use json pipe to display the json format, However object types are a good choice
export class AppComponent {
employee =`{ id: 1, name: "Ram", salary: 5000 }`;
constructor() {}
}
HTML Component:
<div>{{ employee }}</div>
Angular json pipe to print in pretty format
pretty format is a beautify a json string with tabs and spaces.
JSON data can be displayed using a pre
tag with an included json pipe.
<pre><div>{{employees | json}}</div></pre>
Output:
[
{
"id": 1,
"name": "Ram",
"Salary": 5000
},
{
"id": 2,
"name": "John",
"Salary": 1000
},
{
"id": 3,
"name": "Franc",
"Salary": 3000
},
{
"id": 4,
"name": "Andrew ",
"Salary": 8000
}
]
Custom json pipe print in tab format
By default json pipe with 2 spaces is provided by Angular.
export class JsonPipe implements PipeTransform {
transform(value: any): string {
return JSON.stringify(value, null, 2);
}
}
We can write a custom pipe using JSON.stringify
with 4 spaces.
export class JsonTabPipe implements PipeTransform {
transform(value: any): string {
return JSON.stringify(value, null, 4);
}
}
Angular JSON pipe circular pipe
Let’s have a model of parent and child model in typescript.
export class Parent {
id: number;
child: Child;
}
export class Child {
name: string;
parent: Parent;
}
Let’s create a data initialization in parent and child objects.
import { Component } from "@angular/core";
import { Child, Parent } from "./parent";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
a = { name: "Groucho", sibling: "" };
b = { name: "Harpo", sibling: this.a };
parent: Parent;
child: Child;
constructor() {
this.child = { name: "ram", parent: this.parent };
this.parent = { id: 1, child: this.child };
}
ngOnInit() {}
}
And existing template gives an error.
<pre><div>{{child | json}}</div></pre>
It gives an error TypeError: Converting circular structure to JSON
So, json pipe will not work in this case.
you can use the below JSON stringify way of using the circular object.
JSON.stringify(parent);
JSON pipe is not working in Angular
When you are using json pipe, You used to get the following errors.
- Unhandled Promise rejection: Template parse errors The pipe ‘json’ could not be found. This error comes when you declare a variable of Promise, but use a variable in html with async pipe. To fix this, use syntax
{{variable| async | json}}
- The JSON pipe does not work in Angular
- pipe not found in Angular
The reason is json pipe is a pipe from the CommonModule
of the @angular/common
module.
You have to import CommonModule
in the application module i.e app.module.ts
.
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { AppComponent } from "./app.component";
import { CommonModule } from "@angular/common";
@NgModule({
imports: [BrowserModule, FormsModule, CommonModule, BrowserAnimationsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
Angular json pipe stackblitz example
JSON pipe example is written in stackblitz examples🔗
Conclusion
To Sum up, Learned what a is json pipe with syntax in Angular and displays formatted currency numbers.