用于将JSON对象转换为漂亮打印JSON的2号角管道

svmlkihl  于 2022-11-19  发布在  其他
关注(0)|答案(5)|浏览(159)

尝试编写一个Angular 2管道,该管道将接受JSON对象字符串,并将其返回到打印/格式化良好的状态以显示给用户。
例如,它将采用以下方式:

{【编号】:1,【货号】:“K3483483344”,“状态”:“CA”,“活动”:false}

并返回在HTML中显示时如下所示的内容:

所以在我看来,我可以得到这样的结果:

<td> {{ record.jsonData | prettyprint }} </td>
wlp8pajw

wlp8pajw1#

我想添加一个更简单的方法来实现这一点,使用内置的json管道:

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

通过这种方式,格式设置得以保留。

jtjikinw

jtjikinw2#

我将为此创建一个自定义管道:

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

并按以下方式使用它:

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

请看下面的堆栈 lightning 战:https://stackblitz.com/edit/angular-prettyprint

x7rlezfr

x7rlezfr3#

我曾经多次要求过这个场景。我看到这个问题在2021年仍然很流行。所以我创建了一个详细的帖子,解释如何不仅仅美化它,而是给它添加颜色,并建立了一个小工具来玩。

2021+解决方案:我构建了自己的自定义版本的管道(受此answer启发),它不仅美化了JSON,还像vscode一样为JSON添加了颜色。我没有使用内置的JSON管道,因为它不能满足我的全部目的。

这也给你的自由,以增加数字行和填充,如果你想。

输出示例如下

全局样式表应该包含每个主题的颜色,例如styles.scss

pre {
  font-weight: 400;

  .number-line {
    color: #adadaf;
  }
  .string {
    color: #95c602;
  }
  .number {
    color: #f2b619;
  }
  .boolean {
    color: #0097f1;
  }
  .null {
    color: #727990;
  }
  .key {
    color: #fff;
  }
}

管道源代码

@Pipe({
  name: 'prettyjson',
  pure:true
})
export class PrettyJsonPipe implements PipeTransform {
  transform(value: any, args: any[]): any {
    try {
      /**
       * check and try to parse value if it's not an object
       * if it fails to parse which means it is an invalid JSON
       */
      return this.applyColors(
        typeof value === 'object' ? value : JSON.parse(value),
        args[0],
        args[1]
      );
    } catch (e) {
      return this.applyColors({ error: 'Invalid JSON' }, args[0], args[1]);
    }
  }

  applyColors(obj: any, showNumebrLine: boolean = false, padding: number = 4) {
    // line number start from 1
    let line = 1;

    if (typeof obj != 'string') {
      obj = JSON.stringify(obj, undefined, 3);
    }

    /**
     * Converts special charaters like &, <, > to equivalent HTML code of it
     */
    obj = obj.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    /* taken from https://stackoverflow.com/a/7220510 */

    /**
     * wraps every datatype, key for e.g
     * numbers from json object to something like
     * <span class="number" > 234 </span>
     * this is why needed custom themeClass which we created in _global.css
     * @return final bunch of span tags after all conversion
     */
    obj = obj.replace(
      /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
      (match: any) => {
        // class to be applied inside pre tag
        let themeClass = 'number';
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            themeClass = 'key';
          } else {
            themeClass = 'string';
          }
        } else if (/true|false/.test(match)) {
          themeClass = 'boolean';
        } else if (/null/.test(match)) {
          themeClass = 'null';
        }
        return '<span class="' + themeClass + '">' + match + '</span>';
      }
    );

    /**
     * Regex for the start of the line, insert a number-line themeClass tag before each line
     */
    return showNumebrLine
      ? obj.replace(
          /^/gm,
          () =>
            `<span class="number-line pl-3 select-none" >${String(line++).padEnd(padding)}</span>`
        )
      : obj;
  }
}

现在在HTML内部传递这些参数,如下所示。如果不传递,默认值showNumberline为false,padding为4

<pre [innerHTML]="dummyJsonObject | prettyjson: [true, 3]"></pre>

希望这对你有帮助🙂。

jv2fixgn

jv2fixgn4#

由于这是google上的第一个结果,让我补充一个快速总结:

  • 如果您只需要打印JSON而不需要正确的格式,那么ShaneHsu建议的内置json管道可以完美地工作:<pre>{{data | json}}</pre>

1.但是,如果您希望有不同的输出,您将需要创建自己的管道,如Thierry Templier所建议的:

  1. ng g generate pipe prettyjson
    1.在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.最后,因为我们返回HTML内容,所以管道必须在innerHTML函数中使用:

<div [innerHTML]="data | prettyjson"></div>
jpfvwuh4

jpfvwuh45#

因为我的变量是与ngModel双向绑定的,所以我不能在html上这样做。我在组件端使用了JSON.stringify(displayValue, null, 2),它完成了这项工作。

相关问题