use a <pre>
tag to JavaScript pretty prints JSON in HTML. The <pre>
need id to show data on it. Where pre
tells the browser engine that the content inside is pre-formatted and can be displayed without any modification.
To convert it to JSON and pretty print use stringify method.
JSON.stringify(data, null, 2)
If your data is already in JSON format use the following to parse the json first.
JSON.stringify(JSON.parse(data), null, 2)
JavaScript pretty prints JSON in HTML
Simple example code to make semantic and denotes that the content inside is a code snippet. It has nothing to do with formatting.
Make sure the JSON output is in a <pre>
tag.
<!DOCTYPE html>
<html>
<body>
<pre id="json"></pre>
<script>
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);
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this JS JSON topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version