【问题标题】:Angular 4 : How to pretty print json with custom angular pipeAngular 4:如何使用自定义角管漂亮地打印 json
【发布时间】:2020-07-30 11:49:07
【问题描述】:

有了这个答案,pretty-print JSON using JavaScript

我有这个功能。

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

然后创建了一个管道:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({ name: 'safeHtml', pure: true })
export class SafeHtml implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) { }

    transform(input) {
        return this.sanitizer.bypassSecurityTrustHtml(input);
    }
}

现在我正在尝试打印漂亮,但由于某种原因,我似乎遗漏了一些东西,它没有打印漂亮或格式化。

<div [innerHtml]="syntaxHighlight(object) | safeHtml"></div>

节目 ::

【问题讨论】:

标签: angular typescript


【解决方案1】:

尝试使用如下的前置标签,

syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return '<pre>' + json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    }) + '</pre>';
}

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 2011-08-05
    • 2015-07-03
    相关资源
    最近更新 更多