javascript格式化json顯示實(shí)例分析
本文實(shí)例講述了javascript格式化json顯示方法。分享給大家供大家參考。具體分析如下:
將json對象或者json字符串格式化方便在網(wǎng)頁上限制
var formatJson = function(json, options) {
var reg = null,
formatted = '',
pad = 0,
PADDING = '';
//one can also use '\t' or a different number of spaces
// optional settings
options = options || {};
// remove newline where '{' or '[' follows ':'
options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
// use a space after a colon
options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
// begin formatting...
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 newlines
reg = /(\r\n\r\n)/g;
json = json.replace(reg, '\r\n');
// remove newlines before commas
reg = /\r\n\,/g;
json = json.replace(reg, ',');
// optional formatting...
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) {
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;
};
關(guān)于json格式化感興趣的朋友還可參考在線工具:
希望本文所述對大家的javascript程序設(shè)計(jì)有所幫助。
相關(guān)文章
js實(shí)現(xiàn)iframe動態(tài)調(diào)整高度的代碼
iframe,尤其是不帶邊框的iframe因?yàn)槟芎途W(wǎng)頁無縫的結(jié)合從而不刷新頁面的情況下更新頁面的部分?jǐn)?shù)據(jù)成為可能,可是iframe的大小卻不像層那樣可以“伸縮自如”,所以帶來了使用上的麻煩,給iframe設(shè)置高度的時(shí)候多了也不好,少了更是不行,現(xiàn)在,讓我來告訴大家一種iframe動態(tài)調(diào)整高度的方法,主要是以下JS函數(shù):2008-01-01
JS highcharts動態(tài)柱狀圖原理及實(shí)現(xiàn)
這篇文章主要介紹了JS highcharts動態(tài)柱狀圖原理及實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
用javascript讀取xml文件讀取節(jié)點(diǎn)數(shù)據(jù)
這篇文章主要介紹了用javascript讀取xml文件讀取節(jié)點(diǎn)數(shù)據(jù)的具體實(shí)現(xiàn),需要的朋友可以參考下2014-08-08
JavaScript中的apply()方法和call()方法使用介紹
我們發(fā)現(xiàn)apply()和call()的真正用武之地是能夠擴(kuò)充函數(shù)賴以運(yùn)行的作用域,如果我們想用傳統(tǒng)的方法實(shí)現(xiàn)2012-07-07
收集的比較全的automation服務(wù)器不能創(chuàng)建對象 異常原因和解決方法
對于出現(xiàn)automation服務(wù)器不能創(chuàng)建對象的問題,下面有幾種解決方法大家可以試試。2008-10-10

