ArticleZip > Angular 2 Pipe That Transforms Json Object To Pretty Printed Json

Angular 2 Pipe That Transforms Json Object To Pretty Printed Json

In Angular 2, dealing with JSON objects is a common task for many developers. Often, we need to manipulate the JSON data to make it more readable or presentable. One useful tool in Angular 2 that can help with this is creating a custom pipe to transform a JSON object into a nicely formatted, pretty-printed JSON format.

To achieve this, we can create a custom pipe in Angular 2 that will take a JSON object as input and output the prettified version of it. This can be handy when you want to display JSON data in a more human-readable way within your Angular application.

Let's dive into the steps to create this custom pipe:

### Step 1: Create a new Angular Pipe
Start by generating a new pipe using Angular CLI. Open your terminal and run the following command:

Bash

ng generate pipe jsonFormatter

### Step 2: Implement the Pipe Transformation
Navigate to the `json-formatter.pipe.ts` file generated by the CLI in the `src/app` directory. Inside the pipe file, you will see a `transform` method. Modify the method to accept a JSON object as input and return the pretty-printed JSON string.

Typescript

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'jsonFormatter'
})
export class JsonFormatterPipe implements PipeTransform {
  transform(value: any): string {
    return JSON.stringify(value, null, 2);
  }
}

In the `transform` method, `JSON.stringify` is used with the parameters `null, 2` to format the JSON data with an indentation of 2 spaces.

### Step 3: Implement the Pipe in Your Component
Now, you can use the `jsonFormatter` pipe in your Angular component template to format the JSON object. For example, if you have a JSON object stored in a variable `jsonData`, you can use the pipe like this:

Html

<p>{{ jsonData | jsonFormatter }}</p>

### Step 4: Test the Pipe
To test the functionality of the pipe, you can provide sample JSON data in your component and see how it is transformed using the custom pipe.

### Conclusion
In this tutorial, we have explored how to create a custom Angular 2 pipe that transforms a JSON object into a pretty-printed format. This can be a useful feature when you want to display JSON data in a more readable and aesthetically pleasing way in your Angular application.

By following these steps, you can enhance the presentation of JSON data within your Angular projects and make it easier for users to understand the information displayed. Experiment with the formatting options provided by `JSON.stringify` to customize the output according to your requirements. Enjoy coding with Angular!

×