js格式化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="apps.bdimg/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;
html文件格式化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//格式化代码函数,已经⽤原⽣⽅式写好了不需要改动,直接引⽤就好
62var formatJson = function (json, options) {
63var reg = null,
64 formatted = '',
65 pad = 0,
66 PADDING = ' ';
67 options = options || {};
68 wlineAfterColonIfBeforeBraceOrBracket = (wlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
69 options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
70if (typeof json !== 'string') {
71 json = JSON.stringify(json);
72 } else {
73 json = JSON.parse(json);
74 json = JSON.stringify(json);
75 }
76 reg = /([\{\}])/g;
77 json = place(reg, '\r\n$1\r\n');
78 reg = /([\[\]])/g;
79 json = place(reg, '\r\n$1\r\n');
80 reg = /(\,)/g;
81 json = place(reg, '$1\r\n');
82 reg = /(\r\n\r\n)/g;
83 json = place(reg, '\r\n');
84 reg = /\r\n\,/g;
85 json = place(reg, ',');
86if (!wlineAfterColonIfBeforeBraceOrBracket) {
87 reg = /\:\r\n\{/g;
88 json = place(reg, ':{');
89 reg = /\:\r\n\[/g;
90 json = place(reg, ':[');
91 }
92if (options.spaceAfterColon) {
93 reg = /\:/g;
94 json = place(reg, ':');
95 }
96 (json.split('\r\n')).forEach(function (node, index) {
97//console.log(node);
98var i = 0,
99 indent = 0,
100 padding = '';
101
102if (node.match(/\{$/) || node.match(/\[$/)) {
103 indent = 1;
104 } else if (node.match(/\}/) || node.match(/\]/)) {
106 pad -= 1;
107 }
108 } else {
109 indent = 0;
110 }
111
112for (i = 0; i < pad; i++) {
113 padding += PADDING;
114 }
115
116 formatted += padding + node + '\r\n';
117 pad += indent;
118 });
119return formatted;
120 };
121//引⽤⽰例部分
122//(1)创建json格式或者从后台拿到对应的json格式
123//var originalJson = {"name": "binginsist", "sex": "男", "age": "25"};
124//下⾯⽤⼀个真实的json数据做测试
125var 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格式进⾏格式化
137var resultJson = formatJson(originalJson);
138//(3)将格式化好后的json写⼊页⾯中
ElementById("writePlace").innerHTML = '<pre>' +resultJson + '<pre/>';
140
141
142//着⾊
143 window.TAB = " ";
144function IsArray(obj) {
145return obj &&
146typeof obj === 'object' && typeof obj.length === 'number' && !(obj.propertyIsEnumerable('length')); 147 }
148function Process() {
149var json = $('#writePlace').text();
150 console.log(json);
151 ElementById("Canvas").style.display = "block";
152var html = "";
153try {
154if (json == "") {
155 json = '""';
156 }
157var obj = eval("[" + json + "]");
158 html = ProcessObject(obj[0], 0, false, false, false);
159 ElementById("Canvas").innerHTML = "<PRE class='CodeContainer'>" + html + "</PRE>"; 160 } catch(e) {
161 alert("json语法错误,不能格式化。错误信息:\n" + e.message);
162 ElementById("Canvas").innerHTML = "";
163 }
164 }
165function ProcessObject(obj, indent, addComma, isArray, isPropertyContent) {
166var html = "";
167var comma = (addComma) ? "<span class='Comma'>,</span> ": "";
168var type = typeof obj;
169if (IsArray(obj)) {
171 html += GetRow(indent, "<span class='ArrayBrace'>[ ]</span>" + comma, isPropertyContent);
172 } else {
173 html += GetRow(indent, "<span class='ArrayBrace'>[</span>", isPropertyContent);
174for (var i = 0; i < obj.length; i++) {
175 html += ProcessObject(obj[i], indent + 1, i < (obj.length - 1), true, false);
176 }
177 html += GetRow(indent, "<span class='ArrayBrace'>]</span>" + comma);
178 }
179 } else {
180if (type == "object" && obj == null) {
181 html += FormatLiteral("null", "", comma, indent, isArray, "Null");
182 } else {
183if (type == "object") {
184var numProps = 0;
185for (var prop in obj) {
186 numProps++;
187 }
188if (numProps == 0) {
189 html += GetRow(indent, "<span class='ObjectBrace'>{ }</span>" + comma, isPropertyContent)
190 } else {
191 html += GetRow(indent, "<span class='ObjectBrace'>{</span>", isPropertyContent);
192var j = 0;
193for (var prop in obj) {
194 html += GetRow(indent + 1, '<span class="PropertyName">"' + prop + '"</span>: ' + ProcessObject(obj[prop], indent + 1, ++j < numProps, false, true))
195 }
196 html += GetRow(indent, "<span class='ObjectBrace'>}</span>" + comma);
197 }
198 } else {
199if (type == "number") {
200 html += FormatLiteral(obj, "", comma, indent, isArray, "Number");
201 } else {
202if (type == "boolean") {
203 html += FormatLiteral(obj, "", comma, indent, isArray, "Boolean");
204 } else {
205if (type == "function") {
206 obj = FormatFunction(indent, obj);
207 html += FormatLiteral(obj, "", comma, indent, isArray, "Function");
208 } else {
209if (type == "undefined") {
210 html += FormatLiteral("undefined", "", comma, indent, isArray, "Null");
211 } else {
212 html += FormatLiteral(obj, '"', comma, indent, isArray, "String");
213 }
214 }
215 }
216 }
217 }
218 }
219 }
220return html;
221 };
222
223function FormatLiteral(literal, quote, comma, indent, isArray, style) {
224if (typeof literal == "string") {
225 literal = literal.split("<").join("<").split(">").join(">");
226 }
227var str = "<span class='" + style + "'>" + quote + literal + quote + comma + "</span>";
228if (isArray) {
229 str = GetRow(indent, str);
230 }
231return str;
232 }
233function FormatFunction(indent, obj) {
234var tabs = "";
235for (var i = 0; i < indent; i++) {
236 tabs += window.TAB;
237 }
238var funcStrArray = String().split("\n");
239var str = "";
240for (var i = 0; i < funcStrArray.length; i++) {
241 str += ((i == 0) ? "": tabs) + funcStrArray[i] + "\n";
242 }
243return str;
244 }
245function GetRow(indent, data, isPropertyContent) {
246var tabs = "";
247for (var i = 0; i < indent && !isPropertyContent; i++) {
248 tabs += window.TAB;
249 }
250if (data != null && data.length > 0 && data.charAt(data.length - 1) != "\n") { 251 data = data + "\n";
252 }
253return tabs + data;
254 };
255</script>
256</body>
257</html>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论