javascript格式化json显示实例分析
本文实例讲述了javascript格式化json显示方法。分享给大家供大家参考。具体分析如下:
将json对象或者json字符串格式化方便在网页上限制
varformatJson=function(json,options){
varreg=null,
formatted='',
pad=0,
PADDING='';
//onecanalsouse'\t'oradifferentnumberofspaces
//optionalsettings
options=options||{};
//removenewlinewhere'{'or'['follows':'
options.newlineAfterColonIfBeforeBraceOrBracket=(options.newlineAfterColonIfBeforeBraceOrBracket===true)?true:false;
//useaspaceafteracolon
options.spaceAfterColon=(options.spaceAfterColon===false)?false:true;
//beginformatting...
if(typeofjson!=='string'){
//makesurewestartwiththeJSONasastring
json=JSON.stringify(json);
}else{
//isalreadyastring,soparseandre-stringify
//inordertoremoveextrawhitespace
json=JSON.parse(json);
json=JSON.stringify(json);
}
//addnewlinebeforeandaftercurlybraces
reg=/([\{\}])/g;
json=json.replace(reg,'\r\n$1\r\n');
//addnewlinebeforeandaftersquarebrackets
reg=/([\[\]])/g;
json=json.replace(reg,'\r\n$1\r\n');
//addnewlineaftercomma
reg=/(\,)/g;
json=json.replace(reg,'$1\r\n');
//removemultiplenewlines
reg=/(\r\n\r\n)/g;
json=json.replace(reg,'\r\n');
//removenewlinesbeforecommas
reg=/\r\n\,/g;
json=json.replace(reg,',');
//optionalformatting...
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){
vari=0,
indent=0,
padding='';
if(node.match(/\{$/)||node.match(/\[$/)){
indent=1;
}elseif(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;
});
returnformatted;
};
关于json格式化感兴趣的朋友还可参考在线工具:
JSON代码工具
希望本文所述对大家的javascript程序设计有所帮助。