格式化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 ...
随机推荐
- 思科ASA5520防火墙telnet、SSH及DHCP设置
ASA5520远程登录telnet 注:最低安全级别的接口不支持telnet登陆,如OutsideASA(config)# telnet 172.16.0.0 255.255.0.0 inside ...
- 腾讯云+校园扶持计划是bug还是福利
前言 上午突然收到好友的微信消息.打开一看是关于关腾讯云"云+校园扶持计划".仔细看下了意思就是用户可以花360大洋购买腾讯云服务器配置为1核2G,1M带宽的服务器3年.(腾讯 ...
- 什么是 JSX
JSX 即 JavaScript XML--一种在 React 组件内部构建标签的类 xml 语法.React 在不使用 JSX 的情况下一样可以工作,然而使用 JSX 可以提高组件的可读性,因此推荐 ...
- python替换脚本
任何场合都用的到的全文替换 #!/usr/bin/python import sys if len(sys.argv) < 5: print 'usage: python %s from to ...
- 【mysql】mysql内置函数
mysql常用内置函数 1.mysql字符串函数 contact 字符串连接函数 mysql>select contact("he",'llo');# hello lcase ...
- ZigBee技术
ZigBee技术是一种近距离.低复杂度.低功耗.低速率.低成本的双向无线通讯技术.主要用于距离短.功耗低且传输速率不高的各种电子设备之间进行数据传输以及典型的有周期性数据.间歇性数据和低反应时间数据传 ...
- JSP常见的7个动作指令
JSP常见的7个动作指令 1.jsp:forward指令 执行页面转向,将请求处理转发到下一个页面 2.jsp:param指令 用于传递参数 3.jsp:include指令 用于动态 ...
- 从不同的角度分析Flex的优缺点
从不同的角度分析Flex的优缺点 技术角度: (1)具备了RIA时代富客户端的优点(C/S+B/S) (2)支持多种服务器语言(JAVA..NET.PHP)及主流框架(Spring.Hibernate ...
- Linux系统挂载NTFS文件系统
今天尝试并成功的将一块500G的移动硬盘挂载到了RHEL5的系统上,甚感欣慰.想到也许以后自己或其他同学们会有类似经历,于是尽量细致的记录于此. 无论是一块安装了Windows/Linu ...
- 对ajax回调函数的研究
1.1开发中遇到的问题 最近开发中我和同事都碰到这样的问题,我们使用jQuery的ajax方法做服务端的校验,在success方法里将验证结果存储到一个js的公共变量或者是页面里的隐藏域,接下来的代码 ...