{"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. bzoj 3295 树套树

    比较裸,可以有好多的优化,比如根本没有删除的点没有加在树套树中的必要,预处理 出来每个不会被删除的值可以减少不少时间,也可以写成树状数组套平衡树,都会快很多 /******************** ...

  2. 【BZOJ】【3907】网格

    组合数学/python 3907: 网格 Time Limit: 1 Sec  Memory Limit: 256 MBSubmit: 162  Solved: 76[Submit][Status][ ...

  3. JS中函数的基础知识

    函数 一.  函数定义 函数又叫方法,在程序里面函数是用来执行某些特定功能的代码.为了减少重复使用代码,可以把特定功能的代码做成函数,需要使用时拿出来调用.alert();就是一个很常见的.简单的函数 ...

  4. Java多线程程序设计详细解析

    一.理解多线程 多线程是这样一种机制,它允许在程序中并发执行多个指令流,每个指令流都称为一个线程,彼此间互相独立. 线程又称为轻量级进程,它和进程一样拥有独立的执行控制,由操作系统负责调度,区别在于线 ...

  5. EditorWindow edit ScriptableObject

    using UnityEngine; [System.Serializable] public class Weapon { //[SerializeField] public string weap ...

  6. (转载)李剑英的CSLight入门指南结合NGUI热更新

    原地址:http://www.xuanyusong.com/archives/3075 李剑英的CSLight入门指南文档撰写者:GraphicQQ: 1065147807 一. CSLIGHT 作者 ...

  7. (转)单机上配置hadoop

    哈哈,几天连续收到百度两次电话,均是利好消息,于是乎不知不觉的自己的工作效率也提高了,几天折腾了好久终于在单机上配置好了hadoop,然后也成功的运行了一个用例,耶耶耶耶耶耶. 转自:http://w ...

  8. ListView的item选中效果

    有时app会需要点击某个item并实现选中的效果,例如做pad时用Fragment实现的左侧列表右侧内容的效果,点击左侧某一个item后会高亮选中 有时简单的使用setSelected(boolean ...

  9. ****Web API 版本控制的几种方式

    个人建议:用content type,即放在Header里面!比如加一个Version:1.4.3 这篇文章写得很好,介绍了三种实现web api版本化的三种方式.我从评论里又收集到两种方式,所以一共 ...

  10. hdu 4722 Good Numbers 数位DP

    数位DP!!! 代码如下: #include<iostream> #include<stdio.h> #include<algorithm> #include< ...