JavaScript
发布时间:2022-04-16 发布网站:大佬教程 code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript格式化json显示实例分析,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
本文实例讲述了javascript格式化json显示方法。分享给大家供大家参考。具体分析如下:
将json对象或者json字符串格式化方便在网页上限制
{
var reg = null,formatted = '',pad = 0,PADDING = '';
//one can also use '\t' or a different
number of spaces
// optional set
Tings
options = options ||
{};
// remove newline where '
{' or '[' follows ':'
option
s.newlineAfterColonIfBeforeBraceOrBracket = (option
s.newlineAfterColonIfBeforeBraceOrBracket === tru
E) ? true :
false;
// use a space after a colon
option
s.spaceAfterColon = (option
s.spaceAfterColon ===
fals
E) ?
false : true;
// begin format
Ting...
if (typeof json
!== '
String')
{
// make sure we start with the JSON as a
String
json = JSON.
Stringify(json
);
} else
{
// is already a
String,so parse and re-
Stringify
//in order to remove extra whitespace
json = JSON.parse(json
);
json = JSON.
Stringify(json
);
}
// add newline before and after curly braces
reg = /([\
{\}])/g;
json = json.
replace(reg,'\r\n$1\r\n'
);
// add newline before and after square brackets
reg = /([\[\]])/g;
json = json.
replace(reg,'\r\n$1\r\n'
);
// add newline after comma
reg = /(\,)/g;
json = json.
replace(reg,'$1\r\n'
);
// remove multiple newli
nes
reg = /(\r\n\r\n)/g;
json = json.
replace(reg,'\r\n'
);
// remove newli
nes before commas
reg = /\r\n\,/g;
json = json.
replace(reg,','
);
// optional format
Ting...
if (!option
s.newlineAfterColonIfBeforeBraceOrBracket)
{
reg = /\:\r\n\
{/g;
json = json.
replace(reg,':
{'
);
reg = /\:\r\n\[/g;
json = json.
replace(reg,':['
);
}
if (option
s.spaceAfterCo
lon) {
reg = /\:/g;
json = json.
replace(reg,': '
);
}
$.each(json.split('\r\n'),function(index,nod
E) {
var i = 0,indent = 0,padding = '';
if (node.match(/\
{$/) || node.match(/\[$/))
{
indent = 1;
} else if (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;
}
);
return formatted;
};
关于json格式化感兴趣的朋友还可参考在线工具:
http://tools.jb51.cc/code/json">JSON代码工具
希望本文所述对大家的javascript程序设计有所帮助。
大佬总结
以上是大佬教程为你收集整理的javascript格式化json显示实例分析全部内容,希望文章能够帮你解决javascript格式化json显示实例分析所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。