格式化JSON数据

function formatJson(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;
};

  这个方法是在网上搜索到的一段代码,是用来把后台的页面不可读的JSON数据拼装成页面可读的JSON格式。这个方法在实际项目中可能用处不是很大,之前我使用到的场景是在做前后台对接时使用到的,因为开发的时候前端和后端是两个开发团队。所以接口测试和对接是时分有必要的,在这个时候这个把页面不可读的JSON数据转成可读的JSON就很有必要了。下面是前后端接口测试页面的具体实现。

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>接口测试</title>
<link rel="stylesheet" href="http://www.fangxiangxiaopangpang.cn/lib/layui/build/css/layui.css">
<style lang="">
body {
background-attachment: fixed;
background-image: url('http://www.fangxiangxiaopangpang.cn/lib/images/pic01.jpg');
background-position: center bottom;
background-size: 100% auto;
} .login {
position: fixed;
top: 50%;
left: 50%;
background-color: rgba(0, 0, 0, 0.4);
width: 700px;
transform:translate(-50%,-50%);
-ms-transform:translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
-o-transform:translate(-50%,-50%);
border-radius: 10px;
text-align: center;
} .login h1 {
font-size: 30px;
line-height: 40px;
margin-top: 30px;
color: #fff;
padding-left: 22px;
} .login .layui-form-item {
/* display: inline-block; */
margin: 20px ;
} .login .layui-form-pane .layui-form-label {
width: 110px;
padding: 8px 15px;
height: 38px;
line-height: 20px;
border: 1px solid #e6e6e6;
border-radius: 2px 0 0 2px;
text-align: center;
background-color: #FBFBFB;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
-webkit-box-sizing: border-box!important;
-moz-box-sizing: border-box!important;
box-sizing: border-box!important;
} .content{
display:none;
} pre{
text-align:left;
max-height:300px;
overflow:auto;
}
.fileinput{
line-height: 40px;
margin-left: 50px;
color: white;
}
.filename{
display: none;
}
</style>
</head> <body>
<div class="login">
<h1>接口测试</h1>
<form action='#' id = 'test_form' class="layui-form">
<div class="layui-form-item layui-form-pane">
<label class="layui-form-label">传输方式</label>
<div class="layui-input-block" style='color:white'>
<input type="radio" name="type" value="post" title="post" class='type'>
<input type="radio" name="type" value="get" title="get" checked class='type'>
</div>
</div>
<div class="layui-form-item layui-form-pane">
<label class="layui-form-label">接口地址</label>
<div class="layui-input-block">
<input id='address' type="text" name="address" placeholder="请输入接口地址" autofocus class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-pane">
<label class="layui-form-label">参数</label>
<div class="layui-input-block">
<input id='parmas' type="text" name="parmas" placeholder="请输入json格式的参数" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-pane">
<label class="layui-form-label">上传文件</label>
<div class="layui-input-block">
<input type="file" class='fileinput' id='fileinput'>
</div>
</div>
<div class="layui-form-item layui-form-pane filename">
<label class="layui-form-label">name值</label>
<div class="layui-input-block">
<input id='filename' type="text"placeholder="请输入文件name的属性值" class="layui-input">
</div>
</div>
<div class="layui-form-item layui-form-pane content" >
<pre id='backdata'>
</pre>
</div>
<div class="layui-form-item layui-form-pane">
<span class="layui-btn" id='submit'>获取结果</span>
</div>
</form>
</div>
<script src='http://www.fangxiangxiaopangpang.cn/lib/jquery/jquery.min.js'></script>
<script src='http://www.fangxiangxiaopangpang.cn/lib/layui/build/lay/dest/layui.all.js'></script>
<script>
var type = 'get';
$('.layui-form-radio').on("click",function(){
type = $(this).prev('input').val();
});
$('#fileinput').on('change',function(){
$('.filename').show();
})
$('#submit').on("click",function(){
if(!!$("#fileinput")[0].files[0]){
if($('#filename').val()==''){
layer.msg('请输入文件的name值');
return false;
}
var formdata = new FormData();
formdata.append($("#filename").val(), $("#fileinput")[0].files[0]);
if($('#parmas').val().trim() != ''){
try{
var msg = JSON.parse($('#parmas').val().trim());
}catch(e){
layer.msg('请输入标准的JSON格式数据,例如{"a":"1","b":"2"}');
return false;
}
if(msg){
for(var key in msg){
formdata.append(key,msg[key]);
}
}
}
if($('#address').val()==''){
layer.msg('请输入接口地址');
return false;
}
var url = $('#address').val();
if(url.indexOf('http://')==-1){
url = 'http://'+url;
}
$.ajax({
type : type,
url : url,
data: formdata,
cache: false,
processData: false,
contentType: false,
success:function(data){
console.log(data);
$(".content").show();
$('#backdata').html(formatJson(data));
},
error:function(data){
layer.msg('获取数据失败');
}
});
}else{
if($('#address').val()==''){
layer.msg('请输入接口地址');
return false;
}
var data = {};
if($('#parmas').val().trim() != ''){
try{
var msg = JSON.parse($('#parmas').val().trim());
}catch(e){
layer.msg('请输入标准的JSON格式数据,例如{"a":"1","b":"2"}');
return false;
}
if(msg){
for(var key in msg){
data[key] = msg[key];
}
}
}
var url = $('#address').val();
if(url.indexOf('http://')==-1){
url = 'http://'+url;
}
$.ajax({
type : type,
url : url,
data: data,
success:function(data){
// console.log(data);
$(".content").show();
$('#backdata').html(formatJson(data));
},
error:function(data){
layer.msg('获取数据失败');
}
});
}
return false;
});
    function formatJson(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;
    };
</script>
</body>
</html>
上一篇:VMWARE Thin APP


下一篇:变形课(DFS hdu 1181)