Angular 2 pipe that transforms JSON object to pretty-printed JSON

前端 未结 4 1592
清酒与你
清酒与你 2020-12-02 15:01

Trying to write an Angular 2 pipe that will take a JSON object string and return it pretty-printed/formatted to display to the user.

For example, it would take this:

相关标签:
4条回答
  • 2020-12-02 15:42

    As this is the first result on google, let me add a quick sum up:

    • if you only need to print JSON without proper formatting, the build-in json pipe suggested by Shane Hsu works perfectly: <pre>{{data | json}}</pre>

    • however, if you want to have a different output, you will need to create your own pipe as Thierry Templier suggested:

      1. ng g generate pipe prettyjson
      2. in prettyjson.pipe.ts:
    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'prettyjson'
    })
    export class PrettyjsonPipe implements PipeTransform {
    
      transform(value: any, ...args: any[]): any {
        return JSON.stringify(value, null, 2)
        .replace(/ /g, '&nbsp;') // note the usage of `/ /g` instead of `' '` in order to replace all occurences
        .replace(/\n/g, '<br/>'); // same here
      }
    
    }
    
    1. Finally, and because we return HTML content, the pipe must be used inside an innerHTML function:
    <div [innerHTML]="data | prettyjson"></div>
    
    0 讨论(0)
  • 2020-12-02 15:49

    I would create a custom pipe for this:

    @Pipe({
      name: 'prettyprint'
    })
    export class PrettyPrintPipe implements PipeTransform {
      transform(val) {
        return JSON.stringify(val, null, 2)
          .replace(' ', '&nbsp;')
          .replace('\n', '<br/>');
      }
    }
    

    and use it this way:

    @Component({
      selector: 'my-app',
      template: `
        <div [innerHTML]="obj | prettyprint"></div>
      `,
      pipes: [ PrettyPrintPipe ]
    })
    export class AppComponent {
      obj = {
        test: 'testttt',
        name: 'nameeee'
      }
    }
    

    See this stackblitz: https://stackblitz.com/edit/angular-prettyprint

    0 讨论(0)
  • 2020-12-02 15:49

    since my variable is two way binded with ngModel, I could not do it on html. I used on component side JSON.stringify(displayValue, null, 2) and it did the job.

    0 讨论(0)
  • 2020-12-02 15:51

    I would like to add an even simpler way to do this, using the built-in json pipe:

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

    This way, the formatting is preserved.

    0 讨论(0)
提交回复
热议问题