Member-only story

How to prettify a JSON object on the browser

Marika Lam
Nov 1, 2022

--

To prettify a JSON object on the browser, use the <pre> tag.

var data = {
"data": {
"x": "1",
"y": "1",
"url": "http://url.com"
},
"event": "start",
"show": 1,
"id": 50
}


document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

pre tells the browser engine that the content inside is pre-formatted and it can be displayed without any modification. So browser will not remove white spaces, new lines etc. code is for making it more semantic and denotes that the content inside is a code snippet. It has nothing to with formatting. It is advised to use like this, <pre><code> /* Your code snippet here. */ </code></pre>

--

--

No responses yet