JSON高亮格式化页面显示

高亮CSS定义:

  <style type="text/css">
        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>

JS高亮定义:

    function syntaxHighlight(json) {
        json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
        return json.replace(/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])*"(s*:)?|(true|false|null)|-?d+(?:.d*)?(?:[eE][+-]?d+)?)/g, function (match) {
            var cls = 'number';
            if (/^"/.test(match)) {
                if (/:$/.test(match)) {
                    cls = 'key';
                } else {
                    cls = 'string';
                }
            } else if (/true|false/.test(match)) {
                cls = 'boolean';
            } else if (/null/.test(match)) {
                cls = 'null';
            }
            return '<span class="' + cls + '">' + match + '</span>';
        });
    }

后台返回的json字符串,高亮格式化显示到元素内:

$("#id_show").empty();
var jdata = JSON.stringify(JSON.parse(data), null, 4);
$("#id_show").html("<pre>"+syntaxHighlight(jdata)+"</pre>");

最终效果参考:

原文地址:https://www.cnblogs.com/ixixi/p/10756239.html