Home  >  Angular

Angular 2 Json Pipe Example

By Arvind Rai, December 17, 2016
On this page we will provide angular 2 json pipe example. Angular JsonPipe converts data into JSON string. It uses json keyword with pipe operator to convert any expression result into JSON string. In our example we will create object and array of objects and then we will display them into JSON string using JsonPipe. It is used as follows.

<pre> {{person | json}} </pre>

Where person is an object. JsonPipe is working as a function that is taking arguments of given expression and json keyword and returning JSON string. <pre> tag helps to get JSON string as pretty print. Now find the JsonPipe example step by step using typescript.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0

Create Component and Classes used in Example

In our example we are using following classes whose object will be converted into JSON string.
name.ts
export class Name {
    constructor(public fname:string, public lname:string) {
    }
}  
address.ts
export class Address {
    constructor(public vill:string, public district:string,
                                 	public country:string) {
    }
}  
person.ts
import {Name} from './name';
import {Address} from './address';
export class Person {
    constructor(public id:number, public pname:Name, 
	                     public dob:Date, public address:Address) {
    }
}  
jsonpipe.component.ts
import {Component} from '@angular/core';
import {Person} from './person';
import {Name} from './name';
import {Address} from './address';
@Component({
    selector: 'jsonpipe-app',
    template: `
	         <b>JSON for Address Class</b>
				
		 <pre> {{address1 | json}} </pre>
				
		 <b>JSON for Array of Address</b>
				
		 <pre> <div [innerHTML]="addressArray | json"></div> </pre>
				
		 <b>JSON for Person Name Property</b>
				
		 <pre> {{person.pname | json}} </pre>
				
		 <b>JSON for Person class</b>
				
		<pre>{{person | json}}</pre>
	     `
})
export class JsonPipeComponent {
        address1 = new Address('Dhananjaypur', 'Varanasi', 'India');
	address2 = new Address('Moonsi', 'Bhadohi', 'India');
	addressArray = [this.address1, this.address2];
	
	nameObj = new Name('Narendra', 'Modi');
	dob = new Date(1950, 9, 17);
	
	person = new Person(100, this.nameObj, this.dob, this.address1);
}   

JsonPipe

JsonPipe is an angular PIPE. JsonPipe converts an expression value into JSON string. JsonPipe uses JSON.stringify to convert into JSON string. In JSON.stringify, JSON is a subset of JavaScript. JsonPipe uses json keyword to convert value into JSON string using pipe operator as follows.

expression | json

For the example find the object of Address class in our component.
address1 = new Address('Dhananjaypur', 'Varanasi', 'India'); 
Use json keyword with pipe operator (|) to convert the given object into JSON string.
<pre> {{address1 | json}} </pre> 
<pre> tag helps to get JSON string as pretty print. Find the output.
 {
  "vill": "Dhananjaypur",
  "district": "Varanasi",
  "country": "India"
}  

JsonPipe with Array

Here we will create an array of objects of Address class and then we will display it into JSON format using JsonPipe. Find the array created in our component.
address1 = new Address('Dhananjaypur', 'Varanasi', 'India');
address2 = new Address('Moonsi', 'Bhadohi', 'India');
addressArray = [this.address1, this.address2]; 
Use json keyword with pipe operator (|).
<pre> {{addressArray | json}} </pre> 
Using HTML elements such as <div>, we will use JsonPipe as given below.
<pre> <div [innerHTML]="addressArray | json"></div> >/pre> 
<pre> tag helps to get JSON string as pretty print. Find the output.
[
  {
    "vill": "Dhananjaypur",
    "district": "Varanasi",
    "country": "India"
  },
  {
    "vill": "Moonsi",
    "district": "Bhadohi",
    "country": "India"
  }
] 

JsonPipe with Object of Objects

In our example we have a Person class. This class will be initialized by passing objects of Name and Address class in our component.
address1 = new Address('Dhananjaypur', 'Varanasi', 'India');
nameObj = new Name('Narendra', 'Modi');
dob = new Date(1950, 9, 17);
person = new Person(100, this.nameObj, this.dob, this.address1); 
Now if we want to convert person object's any property into JSON string using JsonPipe, we can do as follows.
<pre> {{person.pname | json}} </pre> 
<pre> tag helps to get JSON string as pretty print. Find the output.
{
  "fname": "Narendra",
  "lname": "Modi"
} 
Now use JsonPipe with person object.
<pre> {{person | json}} </pre> 
Find the output.
{
  "id": 100,
  "pname": {
    "fname": "Narendra",
    "lname": "Modi"
  },
  "dob": "1950-10-16T18:30:00.000Z",
  "address": {
    "vill": "Dhananjaypur",
    "district": "Varanasi",
    "country": "India"
  }
} 
If we use <pre> tag, we will get pretty print output.

Create Module, Main and index.html


module.ts
import {NgModule}       from '@angular/core';
import {BrowserModule}  from '@angular/platform-browser';
import {JsonPipeComponent}  from './jsonpipe.component';
@NgModule({
  imports:      [BrowserModule],
  declarations: [JsonPipeComponent],
  bootstrap:    [JsonPipeComponent]
})
export class AppModule { } 
main.ts
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);  
index.html
<html>
  <head>
    <title>Angular 2 Demo</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('myApp').catch(function(err){ console.error(err); });
    </script>
  </head>
  <body>
    <jsonpipe-app>Please Wait...</jsonpipe-app>
  </body>
</html> 

Run Application

Find the steps to run the example.
1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 Json Pipe Example

Reference

Angular 2 JsonPipe

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us