分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

js格式化json数据 + json着色 - 附源码

发布时间:2023-09-06 01:38责任编辑:傅花花关键词:jsjson

  其实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.stringify(json); 72 ????} else { 73 ????????json = JSON.parse(json); 74 ????????json = JSON.stringify(json); 75 ????} 76 ????reg = /([\{\}])/g; 77 ????json = json.replace(reg, ‘\r\n$1\r\n‘); 78 ????reg = /([\[\]])/g; 79 ????json = json.replace(reg, ‘\r\n$1\r\n‘); 80 ????reg = /(\,)/g; 81 ????json = json.replace(reg, ‘$1\r\n‘); 82 ????reg = /(\r\n\r\n)/g; 83 ????json = json.replace(reg, ‘\r\n‘); 84 ????reg = /\r\n\,/g; 85 ????json = json.replace(reg, ‘,‘); 86 ????if (!options.newlineAfterColonIfBeforeBraceOrBracket) { 87 ????????reg = /\:\r\n\{/g; 88 ????????json = json.replace(reg, ‘:{‘); 89 ????????reg = /\:\r\n\[/g; 90 ????????json = json.replace(reg, ‘:[‘); 91 ????} 92 ????if (options.spaceAfterColon) { 93 ????????reg = /\:/g; 94 ????????json = json.replace(reg, ‘:‘); 95 ????} 96 ????(json.split(‘\r\n‘)).forEach(function (node, index) { 97 ????????//console.log(node); 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 + ‘\r\n‘;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 = formatJson(originalJson);138 //(3)将格式化好后的json写入页面中139 document.getElementById("writePlace").innerHTML = ‘<pre>‘ +resultJson + ‘<pre/>‘;140 141 142 //着色143 window.TAB = " ???";144 function IsArray(obj) {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.log(json);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 = ProcessObject(obj[0], 0, false, false, false);159 ????????document.getElementById("Canvas").innerHTML = "<PRE class=‘CodeContainer‘>" + html + "</PRE>";160 ????} catch(e) {161 ????????alert("json语法错误,不能格式化。错误信息:\n" + e.message);162 ????????document.getElementById("Canvas").innerHTML = "";163 ????}164 }165 function ProcessObject(obj, indent, addComma, isArray, isPropertyContent) {166 ????var html = "";167 ????var comma = (addComma) ? "<span class=‘Comma‘>,</span> ": "";168 ????var type = typeof obj;169 ????if (IsArray(obj)) {170 ????????if (obj.length == 0) {171 ????????????html += GetRow(indent, "<span class=‘ArrayBrace‘>[ ]</span>" + comma, isPropertyContent);172 ????????} else {173 ????????????html += GetRow(indent, "<span class=‘ArrayBrace‘>[</span>", isPropertyContent);174 ????????????for (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 {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 += GetRow(indent, "<span class=‘ObjectBrace‘>{ }</span>" + comma, isPropertyContent)190 ????????????????} else {191 ????????????????????html += GetRow(indent, "<span class=‘ObjectBrace‘>{</span>", isPropertyContent);192 ????????????????????var j = 0;193 ????????????????????for (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 {199 ????????????????if (type == "number") {200 ????????????????????html += FormatLiteral(obj, "", comma, indent, isArray, "Number");201 ????????????????} else {202 ????????????????????if (type == "boolean") {203 ????????????????????????html += FormatLiteral(obj, "", comma, indent, isArray, "Boolean");204 ????????????????????} else {205 ????????????????????????if (type == "function") {206 ????????????????????????????obj = FormatFunction(indent, obj);207 ????????????????????????????html += FormatLiteral(obj, "", comma, indent, isArray, "Function");208 ????????????????????????} else {209 ????????????????????????????if (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 ????}220 ????return html;221 };222 223 function FormatLiteral(literal, 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 = GetRow(indent, str);230 ????}231 ????return str;232 }233 function FormatFunction(indent, obj) {234 ????var tabs = "";235 ????for (var i = 0; i < indent; i++) {236 ????????tabs += window.TAB;237 ????}238 ????var funcStrArray = obj.toString().split("\n");239 ????var str = "";240 ????for (var i = 0; i < funcStrArray.length; i++) {241 ????????str += ((i == 0) ? "": tabs) + funcStrArray[i] + "\n";242 ????}243 ????return str;244 }245 function GetRow(indent, 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.charAt(data.length - 1) != "\n") {251 ????????data = data + "\n";252 ????}253 ????return tabs + data;254 };255 </script>256 </body>257 </html>

js格式化json数据 + json着色 - 附源码

原文地址:https://www.cnblogs.com/Sinhtml/p/8336930.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved