jFormat 格式化输出json 字符串

jFormat 将json 字符串或对象,转换为格式字符串(含缩进符号)。

支持cmd、amd、commonjs

/**
 * 格式化输出 json
 * created by zcyue at 2019-01-25
 */

; (function (global, factory) {

  "use strict";

  if (typeof module === "object" && typeof module.exports === "object") {

    // For CommonJS and CommonJS-like environments where a proper `window`
    // is present, execute the factory and get jFormat.
    // For environments that do not have a `window` with a `document`
    // (such as Node.js), expose a factory as module.exports.
    // This accentuates the need for the creation of a real `window`.
    // See ticket #14549 for more info.
    module.exports = global.document ?
      factory(global, true) :
      function (w) {
        if (!w.document) {
          throw new Error("jFormat requires a window with a document");
        }
        return factory(w);
      };
  } else {

    try{
      if(define && define.cmd) {
        define(function () {
          return factory(global);
        });
      }
    }catch(e){
      factory(global);
    }
  }

})(typeof window !== "undefined" ? window : this, function (window, noGlobal) {

  'use strict'

  const NEW_LINE = '\n';
  const TAB = '\t';

  const EXPAND = '+';
  const UN_EXPAND = '-';

  /**
   * 判断是否为数组
   * @param {*} it 
   */
  function isArray(it) {
    return Object.prototype.toString.call(it) === '[object Array]';
  }

  /**
   * 判断是否为对象
   * @param {*} it 
   */
  function isObject(it) {
    return Object.prototype.toString.call(it) === '[object Object]';
  }

  function trimL(str) {
    let pattern = /^\s*(\S)/g;
    if (typeof str !== 'string') str = str + ''
    return str.replace(pattern, '$1');
  }

  function tab(count) {
    return TAB.repeat(count);
  }

  function formatArray(arr, level) {
    level = level || 0;

    if (arr.length <= 0) return `${UN_EXPAND}[${NEW_LINE}${tab(level)}]`;

    let str = '';
    Array.prototype.forEach.call(arr, v => {
      let s;

      if (isArray(v)) {
        s = formatArray(v, level + 1);
      } else if (isObject(v)) {
        s = formatObject(v, level + 1);
      } else {
        s = tab(level + 1) + '"' + v + '"';
      }

      if (str) str += ',' + NEW_LINE;
      str += s;
    });

    return tab(level) + `${UN_EXPAND}[${NEW_LINE}` + str + `${NEW_LINE}${tab(level)}]`;
  }

  function formatObject(obj, level) {
    level = level || 0;

    let str = '';
    Array.prototype.forEach.call(Object.keys(obj), key => {
      if (obj.hasOwnProperty(key)) {
        let v = obj[key];

        let s;

        if (isArray(v)) {
          s = formatArray(v, level + 1);
        } else if (isObject(v)) {
          s = formatObject(v, level + 1);
        } else {
          s = '"' + v + '"';
        }

        if (str) str += ',';
        str += NEW_LINE + tab(level + 1) + '"' + key + '"' + ': ' + trimL(s);
      }
    });

    return tab(level) + UN_EXPAND + '{' + str + NEW_LINE + tab(level) + '}';
  }

  /**
   * json 字符串格式化
   * @param {*} str
   */
  function formatJSON(str) {
    let obj = typeof str === 'string' ? JSON.parse(str) : str
    return isArray(obj) ? formatArray(obj) : formatObject(obj);
  }

  // 是代码支持 amd 模块加载
  if (typeof define === "function" && define.amd) {
    define("jFormat", [], function () {
      return formatJSON;
    });
  }

  window.jFormat = formatJSON;

  return formatJSON;

})

示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

  <script src="jFormat.js"></script>

</head>
<body>
  
<script>

  var obj = {"a":{"aa":13},"b":[{"bb":"bbValue"},{"bb2":"bb2v","bc2":19}],"c":{"name":"JAY","age":43}};
  console.log(jFormat(obj));

</script>

</body>
</html>

控制台输出:

至此,结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值