• 有强迫症的我只能自己写一个json格式化工具


    缘由

    为什么博客园的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 ? '[' : '{') + '
    ';
    				for(var i in obj)
    				{
    					result += (idx++ > 0 ? ',
    ' : ''); // 如果不是数组或对象的第一个内容,追加逗号
    					var nextIsObj = (typeof obj[i] == 'object' && obj[i] != null), indentStr = getIndentStr(level+1);
    					result += (isArray && nextIsObj) ? '' : indentStr; // 如果当前是数组并且子项是对象,无需缩进
    					result += isArray ? '' : ('"' + i + '": ' + (nextIsObj && !leftBracesInSameLine ? '
    ' : '') );
    					result += (!nextIsObj || (nextIsObj && leftBracesInSameLine && !isArray)) ? '' : indentStr;
    					result += format(obj[i], level+1); // 递归调用
    				}
    				result += '
    ' + 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
    	}
    });
    

    效果

    为了方便演示,简单写了一个测试页面,里面没啥东西,别见笑:

    http://tool.liuxianan.com

    (以下是以前写的一个json高亮的效果图,不是本文的效果图,别误会了,哈哈)

  • 相关阅读:
    NABCD项目分析
    第七周学习进度
    第六周学习进度
    构建之法阅读笔记03
    [算法] 求x的n次方的一种for循环实现
    [算法]分解质因数
    通过索引操作数组
    [swift入门] 数据类型
    二叉排序树 常用函数小结
    剑指 Offer 54. 二叉搜索树的第k大节点 做题小结
  • 原文地址:https://www.cnblogs.com/liuxianan/p/json-format.html
Copyright © 2020-2023  润新知