格式化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>
格式化JSON数据的更多相关文章
- vim调用python格式化json数据
vim调用python格式化json数据 November 30, 2013GNU/Linuxpython3, Vimopenwares python有个标准模块叫json,用于编码/解码,序列化/按 ...
- js格式化JSON数据
前言: 最近做的项目中遇到个需要在前端页面中将某个设备需要的数据格式展示出来,方便用户配置.一开始单纯的将数据格式写入到pre标签中, 但是通过pre标签写入的数据格式在代码可视化上不是很优雅.由于上 ...
- PHP自定义函数格式化json数据怎么调用?
<?php/*** Formats a JSON string for pretty printing** @param string $json The JSON to make pretty ...
- 在JAVA中把JSON数据格式化输出到控制台
public class ForMatJSONStr { public static void main(String[] args) { String jsonStr = "{\" ...
- linux下格式化json文件数据
一.使用 python -m json.tool cat test.json | python -m json.tool 二.jq格式化 在web 2.0时代json这种直观.灵活.高效数据格式基本已 ...
- yformater - chrome谷歌浏览器json格式化json高亮json解析插件
yformater是一款chrome浏览器插件,用来格式化(高亮)服务端接口返回的json数据. 实际上小菜并不是第一个写这种插件的,但是现有的chrome json格式化插件实在是不太好用,索性小菜 ...
- Android网络请求与数据解析,使用Gson和GsonFormat解析复杂Json数据
版权声明:未经博主允许不得转载 一:简介 [达叔有道]软件技术人员,时代作者,从 Android 到全栈之路,我相信你也可以!阅读他的文章,会上瘾!You and me, we are family ...
- 【VueJS】VueJS开发请求本地json数据的配置
VueJS开发请求本地json数据的配置,旧版本是build/dev-server.js,新版本是build/webpack.dev.conf.js. VueJS开发请求本地json数据的配置,早期的 ...
- vue 导出JSON数据为Excel
1. 安装三个依赖 npm install file-saver --save npm install xlsx --save npm install script-loader --save-dev ...
随机推荐
- Android中Activity被系统会收前页面信息保存
1.重写onSaveInstanceState方法 protected void onSaveInstanceState(Bundle outState) { super.onSaveInstance ...
- a标签文字选中后的颜色样式更改
::selection 选择器,选择被用户选取的元素部分.是css3的用法,讲真,我觉得这个东西没必要特地去写.因为选中样式默认的会根据你的背景颜色还有字体color来设置颜色 这是我默认的样式
- vs2017密钥
Enterprise: NJVYC-BMHX2-G77MM-4XJMR-6Q8QF Professional: KBJFW-NXHK6-W4WJM-CRMQB-G3CDH
- Linux内核开发之将驱动程序添加到内核
驱动程序添加到内核 一.概述: 在Linux内核中增加程序需要完成以下三项工作: 1.将编写的源代码复制到Linux内核源代码的相应目录 2.在目录的Kconfig文件中增加新源代码对应项目的编译配置 ...
- gm8180:arm linux启动加载模块、运行程序
1. init #!/bin/busybox ash#load modules mao 2013-02-16 14:12:48 echo "************************m ...
- ffmpeg入门之 Tutorial02
02实际是在01的基础上添加了 SDL显示yuv部分,这部分相对独立. if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) ...
- PHPmysqli的 预处理执行插入语句
预编译在mysql端 预编译可以自动防止sql注入攻击 <?php //预编译技术 //1.创建一个mysqli对象 //2.创建myslqi预编译对象 $mysqli=); $mysqli-& ...
- dojo单柱状图
dojo单柱状图 1.dojo单柱状图源码 column.html: <!DOCTYPE HTML> <html lang="en"> <head&g ...
- java web面试题
java web面试题 第1题. 编写一个Filter,需要() A. 继承Filter 类 B. 实现Filter 接口 C. 继承HttpFilter 类 D. 实现HttpFilter ...
- 获取Filter的三种途径
一.通过CLSID [cpp] view plaincopyprint? IBaseFilter *pF = 0; HRESULT hr = CoCreateInstance(clsid, 0, CL ...