基于javascript的JSON格式頁(yè)面展示美化

字號(hào):


    {"name": "monkey","age": "24","height": 164.0}
    如果想讓以上json字符串在頁(yè)面上展示的比較易讀,即變成下面的style:
    "name": "monkey",
    "age": "24",
    "height": 164.0cm
    }
    本文介紹的方法基于javascript ,代碼如下:
    <html>
    <head>/
    //style中是css代碼
    <style type="text/css">
    body
    {
    white-space: pre;
    font-family: monospace;
    }
    </style>
    //script中是javascript代碼
    <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()"> //表示頁(yè)面加載時(shí)調(diào)用myFunction()
    </body>
    </html>
    其中window.error_id_msgs是所要轉(zhuǎn)換的json對(duì)象,css和myFunction結(jié)合可實(shí)現(xiàn)頁(yè)面展示轉(zhuǎn)換