1.利用pre標簽
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> body{ padding-top: 20px; } #data_info{ width: 100%; font-size: 16px; white-space: pre-wrap; word-wrap: break-word; } .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; } </style> </head> <body> <div id="content-container" class="container" style="margin: 0 auto; width: 90%;"> <pre id="data_info"></pre> </div> </body> <script type="text/javascript"> var show = document.getElementById('data_info'); var jsondata = {"id": {"first":1, "second":2, "third":3, "fourth": [4, 5, 6, 7], "fifth": 5}, "name": {"ZS": "張三", "LS": "李四"}}; show.innerHTML = pretifyJson(jsondata,true); /** * [pretifyJson json格式化打印] * @param {[type]} json [description] * @param {Boolean} pretify [description] * @return {[type]} [description] */ function pretifyJson(json, pretify=true) { if (typeof json !== 'string') { if(pretify){ json = JSON.stringify(json, undefined, 4); }else{ json = JSON.stringify(json); } } return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { let cls = "<span>"; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = "<span class='key'>"; } else { cls = "<span class='string'>"; } } else if (/true|false/.test(match)) { cls = "<span class='boolean'>"; } else if (/null/.test(match)) { cls = "<span class='null'>"; } return cls + match + "</span>"; } ); } </script> </html>
結果:
2.使用jsonview插件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.bootcdn.net/ajax/libs/jquery-jsonview/1.2.3/jquery.jsonview.css" rel="stylesheet"> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery-jsonview/1.2.3/jquery.jsonview.js"></script> </head> <body> <div id="content-container" class="container" style="margin: 0 auto; width: 90%;"> <div id="data_info"></div> </div> </body> <script type="text/javascript"> var jsondata = {"id": {"first":1, "second":2, "third":3, "fourth": [4, 5, 6, 7], "fifth": 5}, "name": {"ZS": "張三", "LS": "李四"}}; $(function() { /* JSONView第一個參數就是需要轉換的json數據 */ $("#data_info").JSONView(jsondata, {collapsed: false, nl2br: true, recursive_collapser: true }); }); </script> </html>
結果