javascript格式化json显示
来源:互联网 发布:破解版的软件 编辑:程序博客网 时间:2024/05/22 03:44
var formatJson = function(json, options) { var reg = null, formatted = '', pad = 0, PADDING = ' '; // one can also use '\t' or a different number of spaces // optional settings options = options || {}; // remove newline where '{' or '[' follows ':' options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false; // use a space after a colon options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true; // begin formatting... if (typeof json !== 'string') { // make sure we start with the JSON as a string json = JSON.stringify(json); } else { // is already a string, so parse and re-stringify in order to remove extra whitespace json = JSON.parse(json); json = JSON.stringify(json); } // add newline before and after curly braces reg = /([\{\}])/g; json = json.replace(reg, '\r\n$1\r\n'); // add newline before and after square brackets reg = /([\[\]])/g; json = json.replace(reg, '\r\n$1\r\n'); // add newline after comma reg = /(\,)/g; json = json.replace(reg, '$1\r\n'); // remove multiple newlines reg = /(\r\n\r\n)/g; json = json.replace(reg, '\r\n'); // remove newlines before commas reg = /\r\n\,/g; json = json.replace(reg, ','); // optional formatting... 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, ': '); } $.each(json.split('\r\n'), function(index, 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;};
原文地址:http://www.sharejs.com/codes/javascript/5452
0 0
- javascript格式化json显示
- 用javascript格式化json以便显示阅读
- JS:Json格式化显示
- json串格式化显示
- javascript 格式化 json字符串
- Javascript格式化数字显示
- Javascript格式化数字显示
- JavaScript格式化显示日期
- Jquery格式化显示Json数据
- ExtJS中格式化json显示
- json格式化显示(agular2)
- JavaScript格式化数字显示格式
- 如何对json代码进行格式化显示
- 在线JSON验证_格式化显示
- 页面中JSON数据格式化显示
- Jquery 格式化Json 并且显示在div
- HTML,javascript,Json数据在线格式化工具
- json时间数据,使用javascript格式化字符串
- .NET基础--异常处理
- 专注SQL实现、优化 自定义函数实现NULL值替换
- js的url传值中文乱码问题
- iOS中app启动闪退的原因
- Unity游戏开发—休闲类(有源代码)
- javascript格式化json显示
- solr的一些查询参数
- VC2008 Windows Media Player控件的使用技巧(三)
- Android_Studio的学习1--下载和安装
- Samza的Task是如何运行在Yarn上的
- 关于安卓开发选择android 4.2.2(API 17)应用无法打开的解决办法
- 【Android】别话 AsyncTask
- ubuntu14.04为idea14 webstorm 增加启动栏快捷图标
- POJ3740精确覆盖(dfs +状压+位运算)