码迷,mamicode.com
首页 > Web开发 > 详细

json字符串格式化

时间:2015-05-22 19:47:37      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

    var str = ‘{"id":12, "name":"张三","data":{"id2":12, "name2":"张三","data":{"id3":12, "name3":"张三"}}, "addr":"火星基地"}‘;
		
		//换行符号、空格符号
		var hh = "\n";
		var trimF = ‘ ‘;
		var trimF2 = ‘    ‘;
		
		//格式化显示json数据
		function formatJsonToStr(str){
			
			var html = ‘{‘ + "\n"; 
			var jsonData = eval(‘(‘ + str + ‘)‘);
			var jsonLength = getJsonLength(jsonData);
			var i = 0;
			for(var key in jsonData){
				i++;
				html += formatData(key, jsonData[key]);
				if(jsonLength != i){
					html += "," + "\n";
				}
			}
			html += "\n" + ‘}‘ ;
			return html;
		}
		
		//格式化数据
		function formatData(key, currObject){
			
			var html = ‘‘;
			var type = typeof(currObject);
			if(type == ‘string‘ || type == ‘number‘){
				html += ‘    ‘ + key + ‘:"‘ + currObject + ‘"‘;;
			}else if(type == ‘object‘){
				
				html += ‘    ‘ + key + ‘ :   {‘ + "\n";
				var jsonLength = getJsonLength(currObject);
				var i = 0;
				for(var currKey in currObject){
					i++;
					var currData = currObject[currKey];
					html += formatData(currKey, currData);
					if(jsonLength != i){
						html += "," + "\n";
					}
				}
				html += "\n" + ‘    ‘ + ‘}‘ ;
			}
			return html;
		}
		
		//获得json长度
		function getJsonLength(jsonData){
		
			var jsonLength = 0;
			for(var item in jsonData){
				jsonLength++;
			}
			return jsonLength;
		}
		alert(formatJsonToStr(str));

技术分享

將上圖格式化成下面

技术分享



json字符串格式化

标签:

原文地址:http://my.oschina.net/u/1432304/blog/418744

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!