1. // Example usage: http://jsfiddle.net/q2gnX/
  2. var formatJson = function(json, options) {
  3. var reg = null,
  4. formatted = '',
  5. pad = 0,
  6. PADDING = ' '; // one can also use '\t' or a different number of spaces
  7. // optional settings
  8. options = options || {};
  9. // remove newline where '{' or '[' follows ':'
  10. options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
  11. // use a space after a colon
  12. options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
  13. // begin formatting...
  14. if (typeof json !== 'string') {
  15. // make sure we start with the JSON as a string
  16. json = JSON.stringify(json);
  17. } else {
  18. // is already a string, so parse and re-stringify in order to remove extra whitespace
  19. json = JSON.parse(json);
  20. json = JSON.stringify(json);
  21. }
  22. // add newline before and after curly braces
  23. reg = /([\{\}])/g;
  24. json = json.replace(reg, '\r\n$1\r\n');
  25. // add newline before and after square brackets
  26. reg = /([\[\]])/g;
  27. json = json.replace(reg, '\r\n$1\r\n');
  28. // add newline after comma
  29. reg = /(\,)/g;
  30. json = json.replace(reg, '$1\r\n');
  31. // remove multiple newlines
  32. reg = /(\r\n\r\n)/g;
  33. json = json.replace(reg, '\r\n');
  34. // remove newlines before commas
  35. reg = /\r\n\,/g;
  36. json = json.replace(reg, ',');
  37. // optional formatting...
  38. if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
  39. reg = /\:\r\n\{/g;
  40. json = json.replace(reg, ':{');
  41. reg = /\:\r\n\[/g;
  42. json = json.replace(reg, ':[');
  43. }
  44. if (options.spaceAfterColon) {
  45. reg = /\:/g;
  46. json = json.replace(reg, ':');
  47. }
  48. $.each(json.split('\r\n'), function(index, node) {
  49. var i = 0,
  50. indent = 0,
  51. padding = '';
  52. if (node.match(/\{$/) || node.match(/\[$/)) {
  53. indent = 1;
  54. } else if (node.match(/\}/) || node.match(/\]/)) {
  55. if (pad !== 0) {
  56. pad -= 1;
  57. }
  58. } else {
  59. indent = 0;
  60. }
  61. for (i = 0; i < pad; i++) {
  62. padding += PADDING;
  63. }
  64. formatted += padding + node + '\r\n';
  65. pad += indent;
  66. });
  67. return formatted;
  68. };

使用方法:
  1. var json={"name":"HTL","sex":"男","age":"24"};
  2. console.log(formatJson(json));


javascript格式化json显示的更多相关文章

  1. js/javascript format json(js/javascript 格式化json字符串)

    // format json obj string function format_json(txt, compress) { var indentChar = '    '; if (/^\s*$/ ...

  2. Javascript格式化json返回的时间(/Date(1482747413000)/)

    //时间处理,类似/Date(1482747413000)/的形式,得到xxx年xx月xx日 11:11:11 function ChangeDateFormat(jsondate) { jsonda ...

  3. C#后台格式化JSON字符串显示

    很多时候我们从服务器上获取的JSON字符串是没有格式化的,如下: {"BusinessId":null,"Code":200,"Data": ...

  4. VIM中格式化json

    在vim输入以下命令就可以格式化:%!python -m json.tool可以在~/.vimrc增加快捷键map <F4><Esc>:%!python -m json.too ...

  5. AngularJS学习--- 过滤器(filter),格式化要显示的数据 step 9

    1.切换目录,启动项目 git checkout step- npm start 2.需求: 格式化要显示的数据. 比如要将true-->yes,false-->no,这样相互替换. 3. ...

  6. 小白科普之JavaScript的JSON

    一.对json的理解     json是一种数据格式,不是一种编程语言,json并不从属于javascript.     json的语法可以表示以下三种类型的值     1)简单值           ...

  7. C#格式化JSON字符串

    很多时候我们需要将json字符串以 {     "status": 1,     "sum": 9 }这种方式显示,而从服务端取回来的时候往往是这样 {&quo ...

  8. 简单使用JSON,JavaScript读取JSON文本(三)

    JavaScript 读取 JSON 文本转换为对象 JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 Jav ...

  9. javaScript系列 [05]-javaScript和JSON

    本文输出和JSON有关的以下内容❐ JSON和javaScript❐ JSON的语法介绍❐ JSON的数据类型❐ JSON和XMLHTTPRequest❐ JSON的序列化和反序列化处理 1.1 JS ...

随机推荐

  1. 多套方案来提高python web框架的并发处理能力

    Python常见部署方法有 :   fcgi :用spawn-fcgi或者框架自带的工具对各个project分别生成监听进程,然后和http 服务互动 wsgi :利用http服务的mod_wsgi模 ...

  2. C语言学习常见错误分析

    错误分类     语法错 逻辑错 运行错 0.忘记定义变量: int main() { x=3;y=6;  printf("%d/n",x+y); } 1.C语言的变量一定要先定义 ...

  3. HTTPClient实现免登陆请求(带cookie请求)

    背景: 使用httpClient请求某登录型网站,模拟一个操作,一般步骤一个httpclient模式登录->httpClient模拟操作: 此时发现,每次操作都需要进行一次登录,极其浪费时间,是 ...

  4. OpenGL ES 3.0 图元装配

    1. 前言 之前已经把纹理的渲染给弄出来了,但是又遇到一个新的问题,那就是图元装配,比如说我已经把图片给显示出来了,但是呢,并没有做到让它显示到具体的位置,而跟这个位置相关的则需要靠图元装配. 图元装 ...

  5. pear中几个实用的xml代码库

    1.XML_Beautifier 用于将一段排版凌乱的XML文档美化 <?php require_once "XML/Beautifier.php"; $fmt = new ...

  6. 【JavaScript代码实现四】获取和设置 cookie

    // 创建cookie function setCookie(name, value, expires, path, domain, secure) { var cookieText = encode ...

  7. HDU 5698 瞬间移动 数学

    瞬间移动 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5698 Description 有一个无限大的矩形,初始时你在左上角(即第一行第一列),每次 ...

  8. 使用Chrome快速实现数据的抓取(四)——优点

    些一个抓取WEB页面的数据程序比较简单,大多数语言都有相应的HTTP库,一个简单的请求响应即可,程序发送Http请求给Web服务器,服务器返回HTML文件.交互方式如下: 在使用DevProtocol ...

  9. Assembly类

    System.Reflection.Assembly类是一个比较常用到的类,在反射中就经常用到. 由于这个类实在有太多的字段.属性与方法.实在不想将一个个属性方法从MSDN复制出来然后逐个属性.方法敲 ...

  10. golang slice切片的原理以及内置函数cap, len

    golang中slice(切片)是常用的类型, slice是对数组进行封装 package main import ( "fmt" "strconv") fun ...