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.
Answer from Shane Hsu on Stack OverflowI 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.
I had required this scenario and many times require it. I saw this question is still trending in 2021. So I created a detailed post explaining not how to just prettify it but add colors to it and built a small tool to play around with.
2021+ solution: I built my own custom version of pipe (inspried by this answer) which not only prettifies but also adds colors to JSON like vscode. I don't use a built-in JSON pipe because it doesn't serve my full purpose.
This also gives you the freedom to add number lines and padding if you wish to.
Sample output like below

global stylesheet should contain colors as per your theme for e.g 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;
}
}
Source code of the pipe
@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, showNumeberLine: 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, '&').replace(/</g, '<').replace(/>/g, '>');
/* 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 showNumeberLine
? obj.replace(
/^/gm,
() =>
`<span class="number-line pl-3 select-none" >${String(line++).padEnd(padding)}</span>`
)
: obj;
}
}
now pass these params inside HTML like this. If you don't pass it by default value of showNumberline is false and padding is 4
<pre [innerHTML]="dummyJsonObject | prettyjson: [true, 3]"></pre>
Hope this helps.
Videos
Some of the data returned from HTTP GET looks like following:
some_data:{availability: "Available", state: "Enabled", reason: "Available"}I've only been able to get this data to disply by using json pipe. I donโt want to display json on page and would like to know the best way to resolve this. When searching online I see a ton of different approaches to this. Is there a best practice to resolve this in Angular 2?
Example HTML that outputs json on page:
<ion-list>
<ion-item *ngFor="let item of items">
<ion-label text-wrap>{{item.some_data | json}}</ion-label>
</ion-item>
</ion-list>