{"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. poj 1986 Distance Queries LCA

    题目链接:http://poj.org/problem?id=1986 Farmer John's cows refused to run in his marathon since he chose ...

  2. 实现IDisposable接口的模式

    代码: public class Class2 : IDisposable { ~Class2() { Dispose(false); } public void Dispose() { Dispos ...

  3. skinned mesh 蜘蛛样

    被skinned mesh 折磨了 好久,开始感觉skinindices不对,因为pix显示里面全是0 后来跟来跟去发现是这样的,那些uchar的整数被pix用float的格式显示出来 (显示为0.0 ...

  4. poi生成excel

    转自:http://www.cnblogs.com/bmbm/archive/2011/12/08/2342261.html 1.首先下载poi-3.6-20091214.jar,下载地址如下: ht ...

  5. POI中设置Excel单元格格式

    引用:http://apps.hi.baidu.com/share/detail/17249059 POI中可能会用到一些需要设置EXCEL单元格格式的操作小结: 先获取工作薄对象: HSSFWork ...

  6. 引擎设计跟踪(九.14.2i) Android GLES 3.0 完善

    最近把渲染设备对应的GLES的API填上了. 主要有IRenderDevice/IShader/ITexture/IGraphicsResourceManager/IIndexBuffer/IVert ...

  7. ios 判断空字符串

    - (BOOL) isBlankString:(NSString *)string { if (string == nil || string == NULL) { return YES; } if ...

  8. JS通过ajax动态读取xml文件内容

    http://www.sharejs.com/codes/javascript/8178 HTML文件代码如下 <!DOCTYPE html> <html> <head& ...

  9. AssetBundle依赖关系

    原地址:http://www.cnblogs.com/realtimepixels/p/3652086.html Unity AssetBundle Dependencies In the last ...

  10. zoj Fibonacci Numbers ( java , 简单 ,大数)

    题目 //f(1) = 1, f(2) = 1, f(n > 2) = f(n - 1) + f(n - 2) import java.io.*; import java.util.*; imp ...