緣由
為什么博客園的markdown解析出問題了啊?好奇怪啊!
一直以來在編碼規范界有2大爭論不休的話題,一個是關於是用空格縮進還是tab縮進的問題,一個是花括號是否換行的問題,筆者是tab縮進
和花括號換行
的堅決擁護者,不解釋,免得挑起爭論。
可惜的是,幾乎找遍全網都找不到一個支持tab縮進
和花括號換行
的json格式化工具(IDE除外),包括Chrome在內,幾乎所有瀏覽器內置的代碼格式化都是空格縮進
和花括號不換行
的,每次看着花括號放在右上角像一個駝背的老婆婆的樣子,患有嚴重強迫症的我實在不爽,so,只能自己寫一個了。
代碼
代碼不多,一共32行,掛在jQuery下面,如果不想要jQuery,單獨把formatJSON寫成一個方法就是了。
$.extend(
{
/**
* 格式化一段JSON字符串,支持解析非標准JSON
* 不同於絕大多數格式化工具,本方法支持設置縮進方式以及左大括號是否換行
* @start 2016-08-24
* @param {Object} json 要格式化的json串
* @param {Object} indent 縮進方式,可以是若干個空格和tab,默認tab縮進,如 2個空格:" "、4個空格:" "、tab:" "
* @param {Object} leftBracesInSameLine 左大括號是否保持在同一行,默認 false
*/
formatJSON: function (json, indent, leftBracesInSameLine)
{
function getIndentStr(level)
{
var str = '';
for(var i=0; i<level; i++) str += (indent || ' ');
return str;
}
function format(obj, level)
{
level = level == undefined ? 0 : level;
var result = '';
if(typeof obj == 'object' && obj != null) // 如果是object或者array
{
var isArray = obj instanceof Array, idx = 0;
result += (isArray ? '[' : '{') + '\n';
for(var i in obj)
{
result += (idx++ > 0 ? ',\n' : ''); // 如果不是數組或對象的第一個內容,追加逗號
var nextIsObj = (typeof obj[i] == 'object' && obj[i] != null), indentStr = getIndentStr(level+1);
result += (isArray && nextIsObj) ? '' : indentStr; // 如果當前是數組並且子項是對象,無需縮進
result += isArray ? '' : ('"' + i + '": ' + (nextIsObj && !leftBracesInSameLine ? '\n' : '') );
result += (!nextIsObj || (nextIsObj && leftBracesInSameLine && !isArray)) ? '' : indentStr;
result += format(obj[i], level+1); // 遞歸調用
}
result += '\n' + getIndentStr(level) + (isArray ? ']' : '}') + '';
}
else // 如果是 null、number、boolean、string
{
var quot = typeof obj == 'string' ? '"' : '';//是否是字符串
result += (quot + obj + quot + '');
}
return result;
}
return format(eval('(' + json + ')')); // 使用eval的好處是可以解析非標准JSON
}
});
效果
為了方便演示,簡單寫了一個測試頁面,里面沒啥東西,別見笑:
(以下是以前寫的一個json高亮的效果圖,不是本文的效果圖,別誤會了,哈哈)