首页  >  文章  >  web前端  >  html怎样格式化输出JSON数据

html怎样格式化输出JSON数据

php中世界最好的语言
php中世界最好的语言原创
2018-01-16 09:46:343638浏览

这次给大家带来html怎样格式化输出JSON数据,html格式化输出JSON数据的注意事项有哪些,下面就是实战案例,一起来看一下。

将 json 数据以美观的缩进格式显示出来,借助最简单的 JSON.stringify 函数就可以了,因为此函数还有不常用的后面2个参数。

<html>
    <head>
        <meta charset="utf-8" />
        <title>hello</title>
        <style>
            pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
            .string { color: green; }
            .number { color: darkorange; }
            .boolean { color: blue; }
            .null { color: magenta; }
            .key { color: red; } 
        </style>
        <script type="text/javascript">
        function syntaxHighlight(json) {
            if (typeof json != &#39;string&#39;) {
                json = JSON.stringify(json, undefined, 2);
            }
            json = json.replace(/&/g, &#39;&&#39;).replace(/</g, &#39;<&#39;).replace(/>/g, &#39;>&#39;);
            return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                var cls = &#39;number&#39;;
                if (/^"/.test(match)) {
                    if (/:$/.test(match)) {
                        cls = &#39;key&#39;;
                    } else {
                     cls = &#39;string&#39;;
                    }
                } else if (/true|false/.test(match)) {
                    cls = &#39;boolean&#39;;
                } else if (/null/.test(match)) {
                    cls = &#39;null&#39;; 
                }
                return &#39;<span class="&#39; + cls + &#39;">&#39; + match + &#39;</span>&#39;;
            });
        }
    </script>
    </head>
    <body>
    <pre id="result"> 
    

相信看了这些案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

H5里图片中有缝隙应该如何解决

H5的地理定位怎样使用

h5的移动端适配怎样实现

以上是html怎样格式化输出JSON数据的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn