Dumping to JSON is an essential part of debugging, but when you start to work with bigger and more complex objects a normal JSON dump can be too hard to visually parse, so we have a helper pipe that we throw into the codebase to provide a prettier output that converts an object into a formatted JSON string.
@Pipe({
name: 'prettyJson',
})
export class PrettyJsonPipe implements PipeTransform {
/**
* stringify our input
* @param {unknown} val value to transform (normally an object)
* @returns {string} stringified value
*/
transform(val: unknown): string {
return JSON.stringify(val, undefined, 4).replace(/\n/g, '<br />');
}
}
It just takes whatever incoming value and sends it to JSON.stringify, then converts new lines to <br />
s.
To use it on the page, surround it by a <pre>
tag to replace innerHTML.
<pre [innerHTML]=" sampleVariable | prettyJson "></pre>
Usually wrapped in a diagnostic
check to make it available on production when needed.