<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生js格式化json的方法</title>
</head>
<body>
<!--格式化后的json写入的位置-->
<div id="writePlace"></div>
<script>
//格式化代码函数,已经用原生方式写好了不需要改动,直接引用就好
var formatJson = function (json, options) {
var reg = null,
formatted = '',
pad = 0,
PADDING = ' ';
options = options || {};
options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
if (typeof json !== 'string') {
json = JSON.stringify(json);
} else {
json = JSON.parse(json);
json = JSON.stringify(json);
}
reg = /([\{\}])/g;
json = json.replace(reg, '\r\n$1\r\n');
reg = /([\[\]])/g;
json = json.replace(reg, '\r\n$1\r\n');
reg = /(\,)/g;
json = json.replace(reg, '$1\r\n');
reg = /(\r\n\r\n)/g;
json = json.replace(reg, '\r\n');
reg = /\r\n\,/g;
json = json.replace(reg, ',');
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, ':');
}
(json.split('\r\n')).forEach(function (node, index) {
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;
};
//引用示例部分
//(1)创建json格式或者从后台拿到对应的json格式
var originalJson = {"name": "binginsist", "sex": "男","cc":{"aa":["1","3",{"abdd":"dsafs","safs":"sdfa"}]}, "age": "25"};
//(2)调用formatJson函数,将json格式进行格式化
var resultJson = formatJson(originalJson);
//(3)将格式化好后的json写入页面中
document.getElementById("writePlace").innerHTML = '<pre>' +resultJson + '<pre/>';
</script>
</body>
</html>