json格式化(jsonFormat)

参考gitlab

1、将下面两个文件拷贝到自己的代码目录中

component/jsonFormat/index.js:

import CollapsedImg from '../../assets/images/collapsed.gif';
import ExpandedImg from '../../assets/images/expanded.gif';

export default function JsonFormatter(opt) {
  this.options = {
    dom: '',
    tabSize: 2,
    singleTab: '  ',
    quoteKeys: true,
    imgCollapsed: CollapsedImg,
    imgExpanded: ExpandedImg,
    isCollapsible: true,
    ...opt,
  };

  this.isFormated = false;
  this.obj = {
    _dateObj: new Date(),
    _regexpObj: new RegExp(),
  };
  this.init();
}

JsonFormatter.prototype = {
  init() {
    this.tab = this.multiplyString(this.options.tabSize, this.options.singleTab);
  },
  doFormat(jsonStr) {
    let html;
    try {
      html = this.ProcessObject(JSON.parse(jsonStr), 0, false, false, false);
      this.options.dom.innerHTML = `<pre class='jf-CodeContainer'>${html}</pre>`;
      this.isFormated = true;
      this.bindEvent();
    } catch (e) {
      alert(`JSON数据格式不正确:\n${e.message}`);
      this.options.dom.innerHTML = '';
      this.isFormated = false;
    }
  },
  bindEvent() {
    const that = this;
    const elements = document.getElementsByClassName('imgToggle');
    Array.prototype.forEach.call(elements, (el) => {
      const element = el;
      element.onclick = function callback() {
        if (!that.isFormated) {
          return;
        }
        that.makeContentVisible(this.parentNode.nextElementSibling, !parseInt(this.getAttribute('data-status'), 10));
      };
    });
  },
  getRow(indent, data, isPropertyContent) {
    let tabs = '';
    let newData = data;
    if (!isPropertyContent) {
      tabs = this.multiplyString(indent, this.tab);
    }
    if (data && data.length > 0 && data.charAt(data.length - 1) !== '\n') {
      newData = `${data}\n`;
    }
    return tabs + newData;
  },
  formatLiteral(literal, quote, comma, indent, isArray, style) {
    let newLiteral = literal;
    if (typeof literal === 'string') {
      newLiteral = literal.split('<').join('&lt;').split('>').join('&gt;');
    }
    let str = `<span class='jf-${style}'>${quote}${newLiteral}${quote}${comma}</span>`;
    if (isArray) str = this.getRow(indent, str);
    return str;
  },
  multiplyString(num, str) {
    let result = '';
    for (let i = 0; i < num; i += 1) {
      result += str;
    }
    return result;
  },
  makeContentVisible(element, visible) {
    const img = element.previousElementSibling.querySelectorAll('img')[0];
    if (visible) {
      element.style.display = '';
      img.setAttribute('src', this.options.imgExpanded);
      img.setAttribute('data-status', 1);
    } else {
      element.style.display = 'none';
      img.setAttribute('src', this.options.imgCollapsed);
      img.setAttribute('data-status', 0);
    }
  },
  ProcessObject(obj, indent, addComma, isArray, isPropertyContent) {
    let html = '';
    const comma = addComma ? "<span class='jf-Comma'>,</span> " : '';
    const type = typeof obj;
    let clpsHtml = '';
    if (Array.isArray(obj)) {
      if (obj.length === 0) {
        html += this.getRow(indent, `<span class='jf-ArrayBrace'>[ ]</span>${comma}`, isPropertyContent);
      } else {
        clpsHtml = this.options.isCollapsible
          ? `<span><img class='imgToggle' data-status='1' src='${this.options.imgExpanded}'/></span><span class='jf-collapsible'>`
          : '';
        html += this.getRow(indent, `<span class='jf-ArrayBrace'>[</span>${clpsHtml}`, isPropertyContent);
        for (let i = 0; i < obj.length; i += 1) {
          html += this.ProcessObject(obj[i], indent + 1, i < obj.length - 1, true, false);
        }
        clpsHtml = this.options.isCollapsible ? '</span>' : '';
        html += this.getRow(indent, `${clpsHtml}<span class='jf-ArrayBrace'>]</span>${comma}`);
      }
    } else if (type === 'object') {
      if (!obj) {
        html += this.formatLiteral('null', '', comma, indent, isArray, 'Null');
      } else {
        const numProps = Object.keys(obj).length;
        if (numProps === 0) {
          html += this.getRow(indent, `<span class='jf-ObjectBrace'>{ }</span>${comma}`, isPropertyContent);
        } else {
          clpsHtml = this.options.isCollapsible
            ? `<span><img class='imgToggle' data-status='1' src='${this.options.imgExpanded}'/></span><span class='jf-collapsible'>`
            : '';
          html += this.getRow(indent, `<span class='jf-ObjectBrace'>{</span>${clpsHtml}`, isPropertyContent);
          let j = 0;
          Object.keys(obj).forEach((prop) => {
            const quote = this.options.quoteKeys ? '"' : '';
            j += 1;
            html += this.getRow(
              indent + 1,
              `<span class='jf-PropertyName'>${quote}${prop}${quote}</span>: ${this.ProcessObject(
                obj[prop],
                indent + 1,
                j < numProps,
                false,
                true,
              )}`,
            );
          });
          clpsHtml = this.options.isCollapsible ? '</span>' : '';
          html += this.getRow(indent, `${clpsHtml}<span class='jf-ObjectBrace'>}</span>${comma}`);
        }
      }
    } else if (type === 'number') {
      html += this.formatLiteral(obj, '', comma, indent, isArray, 'Number');
    } else if (type === 'boolean') {
      html += this.formatLiteral(obj, '', comma, indent, isArray, 'Boolean');
    } else if (type === 'undefined') {
      html += this.formatLiteral('undefined', '', comma, indent, isArray, 'Null');
    } else {
      html += this.formatLiteral(
        obj.toString().split('\\').join('\\\\').split('"').join('\\"'),
        '"',
        comma,
        indent,
        isArray,
        'String',
      );
    }
    return html;
  },
};

component/jsonFormat/index.css:

@charset "utf-8";
/* CSS Document */
.jf-ObjectBrace {
  color: #00aa00;
  font-weight: bold;
}
.jf-ArrayBrace {
  color: #0033ff;
  font-weight: bold;
}
.jf-PropertyName {
  color: #cc0000;
  font-weight: bold;
}
.jf-String {
  color: #007777;
}
.jf-Number {
  color: #aa00aa;
}
.jf-Boolean {
  color: #0000ff;
}
.jf-Null {
  color: #0000ff;
}
.jf-Comma {
  color: #000000;
  font-weight: bold;
}
pre.jf-CodeContainer {
  margin-top: 0;
  margin-bottom: 0;
  text-align: left;
}

2、使用

// demo.tsx
import JsonFormatter from '../../components/JsonFormatter';
import '../../components/JsonFormatter/index.css';

const reqDom = document.getElementById('reqformatter');
const reqOptions = {
  dom: reqDom,
 };
const req = new JsonFormatter(reqOptions);
if (detailData?.main_req) {
  req.doFormat(detailData?.main_req);
}

<span id="reqformatter" />

3、效果图

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@JsonFormat 是一个用于格式化时间的注解,它可以应用在类的属性上或者方法上,用于指定该属性或方法返回的时间字符串的格式。然而,有时候我们会发现 @JsonFormat 注解在某些情况下失效了。 造成 @JsonFormat 失效的原因可能有以下几种情况: 1. 使用了自定义的序列化器或反序列化器:如果你在序列化或反序列化过程中使用了自定义的序列化器或反序列化器,那么 @JsonFormat 注解可能会失效。这是因为自定义的序列化器或反序列化器可能会覆盖 @JsonFormat 注解指定的格式。 2. 使用了全局配置:如果你在全局配置中指定了日期格式,那么 @JsonFormat 注解可能会被全局配置覆盖,导致失效。 3. 使用了其他注解:如果你同时使用了其他注解来处理时间格式,例如 @DateTimeFormat 注解,那么 @JsonFormat 注解可能会失效。这是因为不同的注解可能存在优先级冲突。 为了解决 @JsonFormat 失效的问题,你可以尝试以下几种方法: 1. 检查是否使用了自定义的序列化器或反序列化器,并确保它们正确处理了 @JsonFormat 注解指定的格式。 2. 检查全局配置,确保没有指定与 @JsonFormat 注解冲突的日期格式。 3. 如果同时使用了其他注解来处理时间格式,可以尝试移除其他注解,只使用 @JsonFormat 注解。 4. 如果以上方法都无效,可以考虑使用自定义的序列化器或反序列化器来处理时间格式,以确保格式化的准确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值