Javascript based JSON format page display beautification method

  • 2020-03-30 03:30:51
  • OfStack

{"name": "monkey","age": "24","height": 164.0}

If you want the above json string to be easy to read on the page, you can change it to the following style:


{ 
"name": "monkey", 
"age": "24", 
"height": 164.0cm 
}

The method introduced in this article is based on javascript. The code is as follows:


<html> 
<head>/ 
//Style is CSS code
<style type="text/css"> 
body 
{ 
white-space: pre; 
font-family: monospace; 
} 
</style>   
//Script is javascript code
<script> 
window.error_id_msgs = <%= error_id_msgs | raw %>; 
function myFunction() { 
document.body.innerHTML = ""; 
document.body.appendChild(document.createTextNode(JSON.stringify(window.error_id_msgs, null, 4))); 
}      
</script> 
</head> 
<body onload="myFunction()"> //Call myFunction() when the page loads
</body> 
</html>

Where window.error_id_msgs is the json object to be converted, CSS and myFunction can be combined to achieve page presentation conversion


Related articles: