1

With this answer, pretty-print JSON using JavaScript,

i have this function.

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>';
    });
}

Then created a pipe :

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);
    }
}

Now I'm trying to print pretty, but for some reason I seem to be missing something, it's not printing pretty or formated.

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

Shows :: enter image description here

Relm
  • 7,923
  • 18
  • 66
  • 113
  • Check this:https://stackoverflow.com/questions/37308420/angular-2-pipe-that-transforms-json-object-to-pretty-printed-json – Chellappan வ Apr 17 '20 at 04:02
  • @Chellappanவ But `
    {{data | json}}
    ` doesn't produce colors as https://stackoverflow.com/questions/4810841/pretty-print-json-using-javascript does. Fiddle http://jsfiddle.net/KJQ9K/554/
    – Relm Apr 17 '20 at 04:07
  • As per https://stackoverflow.com/questions/4810841/pretty-print-json-using-javascript you have to use pre tag to render the formatted json, Did you see the jsfiddle example? – Chellappan வ Apr 17 '20 at 04:21

1 Answers1

0

Try use pre-tag as below,

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>';
}
Shoma
  • 479
  • 3
  • 9