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程序设计有所帮助。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下