{"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】【2601】Simple calculations

    推公式/二分法 好题! 题解:http://blog.csdn.net/zck921031/article/details/7690288 这题明显是一个方程组……可以推公式推出来…… 然而这太繁琐了 ...

  2. A*(A星)算法python实现

    在春节放假前两天我偶然看到了A\*算法(A\*算法是一个启发式的地图寻路算法),感觉挺有意思.正好放假前也没有什么事情,就花了一个下午写出算法的骨架,节后又花了半天时间完善屏幕输出的细节并且调试完成. ...

  3. Cross Validation done wrong

    Cross Validation done wrong Cross validation is an essential tool in statistical learning 1 to estim ...

  4. 【翻译】Sencha Touch2.4 The Layout System 布局

    [翻译]The Layout System 布局 In Sencha Touch there are two basic building blocks: componentsand containe ...

  5. Topcoder srm 632 div2

    脑洞太大,简单东西就是想复杂,活该一直DIV2; A:水,基本判断A[I]<=A[I-1],ANS++; B:不知道别人怎么做的,我的是100*N*N;没办法想的太多了,忘记是连续的数列 我们枚 ...

  6. 自己写简单CoreDataManager封装对CoreData操作

    关于CoreData的介绍太多,网上一搜大把全是,这里不介绍CoreData,直接上代码,注释写的很详细,应该很容易理解,暂时现做简单的增删该查,后面有时间再做修改完善. CoreDataManage ...

  7. HDU 2955 Robberies (01背包,思路要转换一下,推荐!)

    题意: 小A要去抢劫银行,但是抢银行是有风险的,因此给出一个float值P,当被抓的概率<=p,他妈妈才让他去冒险. 给出一个n,接下来n行,分别给出一个Mj和Pj,表示第j个银行所拥有的钱,以 ...

  8. java集合TreeMap应用---求一个字符串中,每一个字母出现的次数

    package cn.itcast.p1.map.test; import java.util.Iterator; import java.util.Map; import java.util.Tre ...

  9. php curl 分离header和body信息

    php中可以通过curl来模拟http请求,同时可以获取http response header和body,当然也设置参数可以只获取其中的某一个.当设置同时获取response header和body ...

  10. Codeforces Round #263 (Div. 2) A B C

    题目链接 A. Appleman and Easy Task time limit per test:2 secondsmemory limit per test:256 megabytesinput ...