json是一种非常常用的数据格式,经常用了作为返回数据使用,比如接口返回、数据提交等。在写接口文档的时候对返回的json数据进行格式化排版一下就非常不错了,下面是我收集的一个不错的json格式函数:
//json格式美化
function prettyFormat(str) {
try {
// 设置缩进为2个空格
str = JSON.stringify(JSON.parse(str), null, 2);
str = str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
return str.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
} catch (e) {
alert("异常信息:" + e);
}
}
//调用美化
$("#show").html("<pre>" + prettyFormat(data) + "</pre>");html显示模块:
<div id="show"></div>