{"promotion_details":{"promotion_detail":[{"discount_fee":"22.20","id":1308028810791231,"promotion_desc":"促销价:省22.20元","promotion_id":"Tmall$tmallItemPromotion_WIRELESS-62575129_546359362","promotion_name":"促销价"}]},"trade_from":"WAP,WAP"}

将上面json格式化在html输出

{
"promotion_details":{
"promotion_detail":[
{
"discount_fee":"22.20",
"id":1308028810791231,
"promotion_desc":"促销价:省22.20元",
"promotion_id":"Tmall$tmallItemPromotion_WIRELESS-62575129_546359362",
"promotion_name":"促销价"
}
]
},
"trade_from":"WAP,WAP"
}

项目中需要再html页面显示json串,于是找了些方法;

原文参见:

第一种函数:http://www.huqiwen.com/2013/01/07/share-format-json-code/

第二种函数:http://www.sharejs.com/codes/javascript/5452

方法1效果较好,以上面json为例,第二个函数会将"trade_from":"WAP,WAP"  从 逗号 处隔开.有一点问题
方法1正常

方法1:

/**
* json美化
* jsonFormat2(json)这样为格式化代码。
* jsonFormat2(json,true)为开启压缩模式
* @param txt
* @param compress
* @returns {string}
*/
function jsonFormat(txt,compress){
var indentChar = ' ';
if(/^\s*$/.test(txt)){
alert('数据为空,无法格式化! ');
return;
}
try{var data=eval('('+txt+')');}
catch(e){
alert('数据源语法错误,格式化失败! 错误信息: '+e.description,'err');
return;
};
var draw=[],last=false,This=this,line=compress?'':'\n',nodeCount=0,maxDepth=0; var notify=function(name,value,isLast,indent/*缩进*/,formObj){
nodeCount++;/*节点计数*/
for (var i=0,tab='';i<indent;i++ )tab+=indentChar;/* 缩进HTML */
tab=compress?'':tab;/*压缩模式忽略缩进*/
maxDepth=++indent;/*缩进递增并记录*/
if(value&&value.constructor==Array){/*处理数组*/
draw.push(tab+(formObj?('"'+name+'":'):'')+'['+line);/*缩进'[' 然后换行*/
for (var i=0;i<value.length;i++)
notify(i,value[i],i==value.length-1,indent,false);
draw.push(tab+']'+(isLast?line:(','+line)));/*缩进']'换行,若非尾元素则添加逗号*/
}else if(value&&typeof value=='object'){/*处理对象*/
draw.push(tab+(formObj?('"'+name+'":'):'')+'{'+line);/*缩进'{' 然后换行*/
var len=0,i=0;
for(var key in value)len++;
for(var key in value)notify(key,value[key],++i==len,indent,true);
draw.push(tab+'}'+(isLast?line:(','+line)));/*缩进'}'换行,若非尾元素则添加逗号*/
}else{
if(typeof value=='string')value='"'+value+'"';
draw.push(tab+(formObj?('"'+name+'":'):'')+value+(isLast?'':',')+line);
};
};
var isLast=true,indent=0;
notify('',data,isLast,indent,false);
return draw.join('');
}

方法2:

/**
* json格式化便于美观在html页面输出
* @param json
* @param options
* @returns {string}
*/
function jsonFormat(json, options) { var reg = null,
formatted = '',
pad = 0,
PADDING = ' '; // one can also use '\t' or a different number of spaces // optional settings
options = options || {};
// remove newline where '{' or '[' follows ':'
options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
// use a space after a colon
options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true; // begin formatting...
if (typeof json !== 'string') {
// make sure we start with the JSON as a string
json = JSON.stringify(json);
} else {
// is already a string, so parse and re-stringify in order to remove extra whitespace
json = JSON.parse(json);
json = JSON.stringify(json);
} // add newline before and after curly braces
reg = /([\{\}])/g;
json = json.replace(reg, '\r\n$1\r\n'); // add newline before and after square brackets
reg = /([\[\]])/g;
json = json.replace(reg, '\r\n$1\r\n'); // add newline after comma
reg = /(\,)/g;
json = json.replace(reg, '$1\r\n'); // remove multiple newlines
reg = /(\r\n\r\n)/g;
json = json.replace(reg, '\r\n'); // remove newlines before commas
reg = /\r\n\,/g;
json = json.replace(reg, ','); // optional formatting...
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, ': ');
} $.each(json.split('\r\n'), function(index, node) {
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;
}

注意,调用函数返回结果后,加上<pre></pre>实现格式化输出

JSON格式化 JSON美化 输出到html的更多相关文章

  1. yformater - chrome谷歌浏览器json格式化json高亮json解析插件

    yformater是一款chrome浏览器插件,用来格式化(高亮)服务端接口返回的json数据. 实际上小菜并不是第一个写这种插件的,但是现有的chrome json格式化插件实在是不太好用,索性小菜 ...

  2. python 格式化 json输出

    利用python格式化json 字符串输出. $ echo '{"json":"obj"}' | python -m json.tool 利用python -m ...

  3. Python进行JSON格式化输出,以及汉字显示问题

    格式化输出 转载地址  https://blog.csdn.net/real_tino/article/details/76422634 问题分析: Python下json手法的json在打印查看时, ...

  4. python 使用json.dumps() 的indent 参数,获得漂亮的格式化字符串后输出

    想获得漂亮的格式化字符串后输出,可以使用json.dumps() 的indent 参数.它会使得输出和pprint() 函数效果类似 >>> data {'age': 4, 'nam ...

  5. 使用jackson美化输出json/xml

    转载:http://www.cnblogs.com/xiwang/ 如何使用jackson美化输出json/xml 1.美化POJO序列化xml 下面将POJO列化为xml并打印. Person pe ...

  6. 如何使用jackson美化输出json/xml

    如何使用jackson美化输出json/xml 1.美化POJO序列化xml 下面将POJO列化为xml并打印. Person person = new Person(); //设置person属性 ...

  7. HTML-DEV-ToolLink(常用的在线字符串编解码、代码压缩、美化、JSON格式化、正则表达式、时间转换工具、二维码生成与解码等工具,支持在线搜索和Chrome插件。)

    HTML-DEV-ToolLink:https://github.com/easonjim/HTML-DEV-ToolLink 常用的在线字符串编解码.代码压缩.美化.JSON格式化.正则表达式.时间 ...

  8. json 格式化输出

    C#格式化JSON字符串 很多时候我们需要将json字符串以 {     "status": 1,     "sum": 9 }这种方式显示,而从服务端取回来的 ...

  9. JSON对象格式美化

    JSON.stringify(obh, null, "\t"); 这段代码就可以对某个js对象美化输出

随机推荐

  1. boost之function

    boost中function是对函数指针和函数对象的进行封装的模板类. 定义示例:function<int()> func生成一个空的对象,表示函数参数个数为零,返回类型为int. #in ...

  2. JavaScript + HTML DOM (keep for myself)

    1.改变 HTML 输出流 JavaScript 能够创建动态的 HTML 内容 eg. <script>document.write(Date());</script> 绝对 ...

  3. Leetcode#49 Anagrams

    原题地址 Anagram:变位词.两个单词是变位词关系的条件是:组成单词的字符相同,只是顺序不同 第一次看这道题看了半天没明白要干嘛,丫就不能给个样例输入输出么..后来还是看网上其他人的总结知道是怎么 ...

  4. 提高Asp.Net应用程序性能的十大方法(译感)

    译完了提高Asp.Net应用程序的十大方法这篇文章,仔细想其中提到的每一条,在这里结合我的项目来谈谈.第一条:返回多个结果集因为我的项目中所有对数据库的访问的sql语句都是通过调用存储过程实现的,所以 ...

  5. jQuery提升性能技巧及个人总结

    1.将jquery对象缓存起来在for循环中,不要每次都要访问数组的length属性,我们应该先将对象缓存进一个变量然后再操作,如下所示: 代码如下:var myLength = myArray.le ...

  6. HDU3507 Print Article(斜率优化dp)

    前几天做多校,知道了这世界上存在dp的优化这样的说法,了解了四边形优化dp,所以今天顺带做一道典型的斜率优化,在百度打斜率优化dp,首先弹出来的就是下面这个网址:http://www.cnblogs. ...

  7. iOS模型以及使用

    个人习惯,也可以不这样写 创建模型基类: #import <Foundation/Foundation.h> @interface WJBaseModel : NSObject //将字典 ...

  8. POJ 2041

    #include <iostream> #include <string> #include <algorithm> using namespace std; st ...

  9. $("#id a") - $("#id .c a") = ?

    前沿 这是之前淘宝的一道面试题,题目借用了 jQuery 选择器的语法.大概的意思是,从 #id 元素内选出所有不是 .c 后代的 a 元素,即父元素 #id 内的所有后代元素中,选出不是 .c 后代 ...

  10. hdu 1404/zoj 2725 Digital Deletions 博弈论

    暴力打表!! 代码如下: #include<iostream> #include<algorithm> #include<cstdio> #include<c ...