JS格式化JSON,JSON着色

<script>
        var jsObj = '{$data}';//远程数据json,可替换为自己的json也可以使用下方json测试
        jsObj = jsObj.replace(/"/,"");
        jsObj = jsObj.substring(0, jsObj.lastIndexOf('"'));
        $("#show").html(formatJson(jsObj));
        //$("#show").html(jsObj);
        Process();
        //格式化代码函数,已经用原生方式写好了不需要改动,直接引用就好
        function formatJson(json, options) {
            var reg = null,
            formatted = '',
            pad = 0,
            PADDING = '    ';
            options = options || {};
            options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
            options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
            if (typeof json !== 'string') {
                json = JSON.stringify(json);
            } else {
                json = JSON.parse(json);
                json = JSON.stringify(json);
            }
            reg = /([\{\}])/g;
            json = json.replace(reg, '\r\n$1\r\n');
            reg = /([\[\]])/g;
            json = json.replace(reg, '\r\n$1\r\n');
            reg = /(\,)/g;
            json = json.replace(reg, '$1\r\n');
            reg = /(\r\n\r\n)/g;
            json = json.replace(reg, '\r\n');
            reg = /\r\n\,/g;
            json = json.replace(reg, ',');
            if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
                reg = /\:\r\n\{/g;
                json = json.replace(reg, ':{');
                reg = /\:\r\n\[/g;
                json = json.replace(reg, ':[');
            }
            if (options.spaceAfterColon) {
                reg = /\:/g;
                json = json.replace(reg, ':');
            }
            (json.split('\r\n')).forEach(function (node, index) {
                //console.log(node);
                var i = 0,
                    indent = 0,
                    padding = '';

                if (node.match(/\{$/) || node.match(/\[$/)) {
                    indent = 1;
                } else if (node.match(/\}/) || node.match(/\]/)) {
                    if (pad !== 0) {
                        pad -= 1;
                    }
                } else {
                        indent = 0;
                }

                for (i = 0; i < pad; i++) {
                    padding += PADDING;
                }

                formatted += padding + node + '\r\n';
                pad += indent;
            });
            return formatted;
        };
        //引用示例部分
        //(1)创建json格式或者从后台拿到对应的json格式
        //var originalJson = {"name": "binginsist", "sex": "男", "age": "25"};
        //下面用一个真实的json数据做测试
        //var originalJson = {
        //    "_errmsg":"ok",
        //    "result":[
        //    ],
        //    "stat":"wechat",
        //    "_token":"",
        //    "weixinId":"900504",
        //    "_errcode":"0",
        //    "regionId":"00000000"
        //}
        //
        //(2)调用formatJson函数,将json格式进行格式化
        //var resultJson = formatJson(originalJson);
        (3)将格式化好后的json写入页面中
        //document.getElementById("writePlace").innerHTML = '<pre>' +resultJson + '<pre/>';

        //着色
        function IsArray(obj) {
          return obj &&
              typeof obj === 'object' &&  typeof obj.length === 'number' && !(obj.propertyIsEnumerable('length'));
        }
        function Process() {
            var json = $('#show').text();
            console.log(json);
            var html = "";
            try {
                if (json == "") {
                    json = '""';
                }
                var obj = eval("[" + json + "]");
                html = ProcessObject(obj[0], 0, false, false, false);
                $("#show").html(html);
            } catch(e) {
            }
        }
        function ProcessObject(obj, indent, addComma, isArray, isPropertyContent) {
            var html = "";
            var comma = (addComma) ? "<span class='Comma'>,</span> ": "";
            var type = typeof obj;
            if (IsArray(obj)) {
                if (obj.length == 0) {
                    html += GetRow(indent, "<span class='ArrayBrace'>[ ]</span>" + comma, isPropertyContent);
                } else {
                    html += GetRow(indent, "<span class='ArrayBrace'>[</span>", isPropertyContent);
                    for (var i = 0; i < obj.length; i++) {
                        html += ProcessObject(obj[i], indent + 1, i < (obj.length - 1), true, false);
                    }
                    html += GetRow(indent, "<span class='ArrayBrace'>]</span>" + comma);
                }
            } else {
                if (type == "object" && obj == null) {
                    html += FormatLiteral("null", "", comma, indent, isArray, "Null");
                } else {
                    if (type == "object") {
                        var numProps = 0;
                        for (var prop in obj) {
                            numProps++;
                        }
                        if (numProps == 0) {
                            html += GetRow(indent, "<span class='ObjectBrace'>{ }</span>" + comma, isPropertyContent)
                        } else {
                            html += GetRow(indent, "<span class='ObjectBrace'>{</span>", isPropertyContent);
                            var j = 0;
                            for (var prop in obj) {
                                html += GetRow(indent + 1, '<span class="PropertyName">"' + prop + '"</span>: ' + ProcessObject(obj[prop], indent + 1, ++j < numProps, false, true))
                            }
                            html += GetRow(indent, "<span class='ObjectBrace'>}</span>" + comma);
                        }
                    } else {
                        if (type == "number") {
                            html += FormatLiteral(obj, "", comma, indent, isArray, "Number");
                        } else {
                            if (type == "boolean") {
                                html += FormatLiteral(obj, "", comma, indent, isArray, "Boolean");
                            } else {
                                if (type == "function") {
                                    obj = FormatFunction(indent, obj);
                                    html += FormatLiteral(obj, "", comma, indent, isArray, "Function");
                                } else {
                                    if (type == "undefined") {
                                        html += FormatLiteral("undefined", "", comma, indent, isArray, "Null");
                                    } else {
                                        html += FormatLiteral(obj, '"', comma, indent, isArray, "String");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return html;
        };

        function FormatLiteral(literal, quote, comma, indent, isArray, style) {
            if (typeof literal == "string") {
                literal = literal.split("<").join("&lt;").split(">").join("&gt;");
            }
            var str = "<span class='" + style + "'>" + quote + literal + quote + comma + "</span>";
            if (isArray) {
                str = GetRow(indent, str);
            }
            return str;
        }
        function FormatFunction(indent, obj) {
            var tabs = "";
            for (var i = 0; i < indent; i++) {
                tabs += "    ";
            }
            var funcStrArray = obj.toString().split("\n");
            var str = "";
            for (var i = 0; i < funcStrArray.length; i++) {
                str += ((i == 0) ? "": tabs) + funcStrArray[i] + "\n";
            }
            return str;
        }
        function GetRow(indent, data, isPropertyContent) {
            var tabs = "";
            for (var i = 0; i < indent && !isPropertyContent; i++) {
                tabs += "    ";
            }
            if (data != null && data.length > 0 && data.charAt(data.length - 1) != "\n") {
                data = data + "\n";
            }
            return tabs + data;
        };
</script>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <style>
        body {font-size:14px;font-family:consolas;}
        pre {font-family:'consolas';}
        .Canvas {
            font:14px/18px 'consolas';
            background-color: #ECECEC;
            color: #000000;
            border: solid 1px #CECECE;
        }
        .ObjectBrace {
            color: #00AA00;
            font-weight: bold;
        }
        .ArrayBrace {
            color: #0033FF;
            font-weight: bold;
        }
        .PropertyName {
            color: #CC0000;
            font-weight: bold;
        }
        .String {
            color: #007777;
        }
        .Number {
            color: #AA00AA;
        }
        .Boolean {
            color: #0000FF;
        }
        .Function {
            color: #AA6633;
            text-decoration: italic;
        }
        .Null {
            color: #0000FF;
        }
        .Comma {
            color: #000000;
            font-weight: bold;
        }
        PRE.CodeContainer {
            margin-top: 0px;
            margin-bottom: 0px;
        }
    </style>
<div class="alert alert-info alert-dismissable">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
    <h3 class="font-w300 push-15">结果</h3>
    <pre id = "show" class="CodeContainer" style=" width: 100%;min-height: 600px;height: 100%;"></pre>
</div>

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生命无须向死而生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值