Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

1 Answer

0 votes
by (106k points)

Natively the Pretty-printing is implemented in JSON.stringify(). The third argument of the function enables pretty printing and sets the spacing to use.

See the code below:-

var str = JSON.stringify(obj, null, 2); 

If you want to pretty-print JSON using JavaScript then use the below-mentioned code:-

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

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...