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.
32 Answers
Here is how you can print without using native function.
function pretty(ob, lvl = 0) { let temp = []; if(typeof ob === "object"){ for(let x in ob) { if(ob.hasOwnProperty(x)) { temp.push( getTabs(lvl+1) + x + ":" + pretty(ob[x], lvl+1) ); } } return "{\n"+ temp.join(",\n") +"\n" + getTabs(lvl) + "}"; } else { return ob; } } function getTabs(n) { let c = 0, res = ""; while(c++ < n) res+="\t"; return res; } let obj = {a: {b: 2}, x: {y: 3}}; console.log(pretty(obj)); /* { a: { b: 2 }, x: { y: 3 } } */ Comments
The simplest way to display an object for debugging purposes:
console.log("data",data) // lets you unfold the object manually If you want to display the object in the DOM, you should consider that it could contain strings that would be interpreted as HTML. Therefore, you need to do some escaping...
var s = JSON.stringify(data,null,2) // format var e = new Option(s).innerHTML // escape document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display 2 Comments
Brent Bradburn
TIL: 'Object' and 'Map' are basically the same thing but have different syntax and implementation details. You can't
JSON.stringify a Map directly: JSON.stringify(Object.fromEntries(mymap))Brent Bradburn
For console.log, see also: console.log() shows the changed value of a variable before the value actually changes
<pre>tag.JSON.stringify(data, null, 2)to format data, then use AceEditor, CodeMirror, or Monaco Editor to display it.