js格式化json数据 + json着色json美化

  其实json格式化没想象中的那么复杂,难点就是json格式化的工作流程。

正好工作上需要,于是就搞了一套json格式化+json着色的方法,原生的方法,可以直接使用。json数据格式化前后对比图,如下:

下面是源码,可以根据个人需求适当修改:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>js格式化json+json着色的方法</title>
  6     <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  7     <style>
  8     body {font-size:14px;font-family:consolas;}
  9     pre {font-family:'consolas';}
 10     .Canvas {
 11         font:14px/18px 'consolas';
 12         background-color: #ECECEC;
 13         color: #000000;
 14         border: solid 1px #CECECE;
 15     }
 16     .ObjectBrace {
 17         color: #00AA00;
 18         font-weight: bold;
 19     }
 20     .ArrayBrace {
 21         color: #0033FF;
 22         font-weight: bold;
 23     }
 24     .PropertyName {
 25         color: #CC0000;
 26         font-weight: bold;
 27     }
 28     .String {
 29         color: #007777;
 30     }
 31     .Number {
 32         color: #AA00AA;
 33     }
 34     .Boolean {
 35         color: #0000FF;
 36     }
 37     .Function {
 38         color: #AA6633;
 39         text-decoration: italic;
 40     }
 41     .Null {
 42         color: #0000FF;
 43     }
 44     .Comma {
 45         color: #000000;
 46         font-weight: bold;
 47     }
 48     PRE.CodeContainer {
 49         margin-top: 0px;
 50         margin-bottom: 0px;
 51     }
 52 </style>
 53 
 54 </head>
 55 <body>
 56 <!--格式化后的json写入的位置-->
 57 <div id="writePlace"></div><br>
 58 <button onclick="Process)">着色</button>
 59 <div id="Canvas"></div>
 60 <script>
 61 //格式化代码函数,已经用原生方式写好了不需要改动,直接引用就好
 62 var formatJson = function json, options) {
 63     var reg = null,
 64             formatted = '',
 65             pad = 0,
 66             PADDING = '    ';
 67     options = options || {};
 68     options.newlineAfterColonIfBeforeBraceOrBracket = options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
 69     options.spaceAfterColon = options.spaceAfterColon === false) ? false : true;
 70     if typeof json !== 'string') {
 71         json = JSON.stringifyjson);
 72     } else {
 73         json = JSON.parsejson);
 74         json = JSON.stringifyjson);
 75     }
 76     reg = /[{}])/g;
 77     json = json.replacereg, '
$1
');
 78     reg = /[[]])/g;
 79     json = json.replacereg, '
$1
');
 80     reg = /\,)/g;
 81     json = json.replacereg, '$1
');
 82     reg = /

)/g;
 83     json = json.replacereg, '
');
 84     reg = /
\,/g;
 85     json = json.replacereg, ',');
 86     if !options.newlineAfterColonIfBeforeBraceOrBracket) {
 87         reg = /:
{/g;
 88         json = json.replacereg, ':{');
 89         reg = /:
[/g;
 90         json = json.replacereg, ':[');
 91     }
 92     if options.spaceAfterColon) {
 93         reg = /:/g;
 94         json = json.replacereg, ':');
 95     }
 96     json.split'
')).forEachfunction node, index) {
 97         //console.lognode);
 98         var i = 0,
 99             indent = 0,
100             padding = '';
101 
102         if node.match/{$/) || node.match/[$/)) {
103             indent = 1;
104         } else if node.match/}/) || node.match/]/)) {
105             if pad !== 0) {
106                 pad -= 1;
107             }
108         } else {
109                 indent = 0;
110         }
111 
112         for i = 0; i < pad; i++) {
113             padding += PADDING;
114         }
115 
116         formatted += padding + node + '
';
117         pad += indent;
118     });
119     return formatted;
120 };
121 //引用示例部分
122 //1)创建json格式或者从后台拿到对应的json格式
123 //var originalJson = {"name": "binginsist", "sex": "男", "age": "25"};
124 //下面用一个真实的json数据做测试
125 var originalJson = {
126     "_errmsg":"ok",
127     "result":[
128     ],
129     "stat":"wechat",
130     "_token":"",
131     "weixinId":"900504",
132     "_errcode":"0",
133     "regionId":"00000000"
134 }
135 
136 //2)调用formatJson函数,将json格式进行格式化
137 var resultJson = formatJsonoriginalJson);
138 //3)将格式化好后的json写入页面中
139 document.getElementById"writePlace").innerHTML = '<pre>' +resultJson + '<pre/>';
140 
141 
142 //着色
143 window.TAB = "    ";
144 function IsArrayobj) {
145   return obj &&
146       typeof obj === 'object' &&  typeof obj.length === 'number' && !obj.propertyIsEnumerable'length'));
147 }
148 function Process) {
149     var json = $'#writePlace').text);
150     console.logjson);
151     document.getElementById"Canvas").style.display = "block";
152     var html = "";
153     try {
154         if json == "") {
155             json = '""';
156         }
157         var obj = eval"[" + json + "]");
158         html = ProcessObjectobj[0], 0, false, false, false);
159         document.getElementById"Canvas").innerHTML = "<PRE class='CodeContainer'>" + html + "</PRE>";
160     } catche) {
161         alert"json语法错误,不能格式化。错误信息:
" + e.message);
162         document.getElementById"Canvas").innerHTML = "";
163     }
164 }
165 function ProcessObjectobj, indent, addComma, isArray, isPropertyContent) {
166     var html = "";
167     var comma = addComma) ? "<span class='Comma'>,</span> ": "";
168     var type = typeof obj;
169     if IsArrayobj)) {
170         if obj.length == 0) {
171             html += GetRowindent, "<span class='ArrayBrace'>[ ]</span>" + comma, isPropertyContent);
172         } else {
173             html += GetRowindent, "<span class='ArrayBrace'>[</span>", isPropertyContent);
174             for var i = 0; i < obj.length; i++) {
175                 html += ProcessObjectobj[i], indent + 1, i < obj.length - 1), true, false);
176             }
177             html += GetRowindent, "<span class='ArrayBrace'>]</span>" + comma);
178         }
179     } else {
180         if type == "object" && obj == null) {
181             html += FormatLiteral"null", "", comma, indent, isArray, "Null");
182         } else {
183             if type == "object") {
184                 var numProps = 0;
185                 for var prop in obj) {
186                     numProps++;
187                 }
188                 if numProps == 0) {
189                     html += GetRowindent, "<span class='ObjectBrace'>{ }</span>" + comma, isPropertyContent)
190                 } else {
191                     html += GetRowindent, "<span class='ObjectBrace'>{</span>", isPropertyContent);
192                     var j = 0;
193                     for var prop in obj) {
194                         html += GetRowindent + 1, '<span class="PropertyName">"' + prop + '"</span>: ' + ProcessObjectobj[prop], indent + 1, ++j < numProps, false, true))
195                     }
196                     html += GetRowindent, "<span class='ObjectBrace'>}</span>" + comma);
197                 }
198             } else {
199                 if type == "number") {
200                     html += FormatLiteralobj, "", comma, indent, isArray, "Number");
201                 } else {
202                     if type == "boolean") {
203                         html += FormatLiteralobj, "", comma, indent, isArray, "Boolean");
204                     } else {
205                         if type == "function") {
206                             obj = FormatFunctionindent, obj);
207                             html += FormatLiteralobj, "", comma, indent, isArray, "Function");
208                         } else {
209                             if type == "undefined") {
210                                 html += FormatLiteral"undefined", "", comma, indent, isArray, "Null");
211                             } else {
212                                 html += FormatLiteralobj, '"', comma, indent, isArray, "String");
213                             }
214                         }
215                     }
216                 }
217             }
218         }
219     }
220     return html;
221 };
222 
223 function FormatLiteralliteral, quote, comma, indent, isArray, style) {
224     if typeof literal == "string") {
225         literal = literal.split"<").join"&lt;").split">").join"&gt;");
226     }
227     var str = "<span class='" + style + "'>" + quote + literal + quote + comma + "</span>";
228     if isArray) {
229         str = GetRowindent, str);
230     }
231     return str;
232 }
233 function FormatFunctionindent, obj) {
234     var tabs = "";
235     for var i = 0; i < indent; i++) {
236         tabs += window.TAB;
237     }
238     var funcStrArray = obj.toString).split"
");
239     var str = "";
240     for var i = 0; i < funcStrArray.length; i++) {
241         str += i == 0) ? "": tabs) + funcStrArray[i] + "
";
242     }
243     return str;
244 }
245 function GetRowindent, data, isPropertyContent) {
246     var tabs = "";
247     for var i = 0; i < indent && !isPropertyContent; i++) {
248         tabs += window.TAB;
249     }
250     if data != null && data.length > 0 && data.charAtdata.length - 1) != "
") {
251         data = data + "
";
252     }
253     return tabs + data;
254 };
255 </script>
256 </body>
257 </html>

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注