本文简单讲述一下javascript格式化json串的方式,具体如下:
var formatJson = function(json, options) { var reg = null, formatted = '', pad = 0, PADDING = ''; // 也可以使用'\t'或不同数量的空间 // 可选设置 options = options || {}; // 删除换行符,“{”或“[”如下:“ options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false; // 使用一个空格后 options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true; // 开始格式化 if (typeof json !== 'string') { // 让我们开始制作json字符串 json = JSON.stringify(json); } else { // 已经是一个字符串,所以解析和重新stringify //为了去除多余的空格 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, ': '); } $.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; };