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));
將上圖格式化成下面
时间: 2024-12-31 03:59:46