JSON格式化输出到页面上——数组+对象+JSON字符串+汉字——基础积累

发布于:2024-05-15 ⋅ 阅读:(31) ⋅ 点赞:(0)

实现功能:将接口返回的内容格式化后展示到页面上。

对象数组——效果图

在这里插入图片描述

对象——效果图

在这里插入图片描述

汉字——效果图

在这里插入图片描述
直接上代码:

解决步骤1:html代码

<div>
  <div class="contentWrp" style="margin-top: 10px">
    <div style="display: flex; justify-content: space-between">
      <a-space>
        <a-button
          id="copyBtn"
          type="primary"
          :data-clipboard-text="copyConfig"
          @click="handleClipboard"
          >复制</a-button
        >
        <span>耗时:
          <span style="color: red">{{ useTimes }} ms</span>
        </span>
      </a-space>
      <a-button type="danger" ghost @click="handleClear">清空</a-button>
    </div>
    <div id="jsonOutput"></div>
  </div>
</div>

对应的方法:

//清空
    handleClear() {
      this.copyConfig = null;
      this.useTimes = 0;
      document.getElementById('jsonOutput').innerHTML = '';
    },
    //复制
    handleClipboard() {
      let clipboard = new Clipboard('#copyBtn');
      clipboard.on('success', () => {
        this.$message.success(`复制成功`);
        clipboard.destroy();
      });
    },

复制实用了插件,可以在我的博客中进行搜索使用。

解决步骤2:格式化代码

 //格式化
    handleFormat(jsonInput) {
      if (Array.isArray(jsonInput)) {
        //数组
       let formattedJson;
        formattedJson = JSON.stringify(jsonInput, null, 2);
        return '<pre>' + formattedJson + '</pre>';
      } else if (jsonInput.constructor == Object) {
        let formattedJson;
        formattedJson = JSON.stringify(jsonInput, null, 2);
        return '<pre>' + formattedJson + '</pre>';
      } else if (this.isJSONString(jsonInput)) {
        let formattedJson;
        formattedJson = JSON.stringify(JSON.parse(jsonInput), null, 2);
        return '<pre>' + formattedJson + '</pre>';
      } else {
        return jsonInput;
      }
    },
    //判断是否是对象
    isJSONString(value) {
      try {
        JSON.parse(value);
        return true;
      } catch (e) {
        return false;
      }
    },

上面的代码解析:
分【对象数组】【对象】【JSON对象】【汉字】等几种情况

判断是否为数组:Array.isArray(jsonInput)

判断是否为对象:jsonInput.constructor == Object

判断是否是JSON对象:this.isJSONString(jsonInput)

上面还使用了递归。。。


网站公告

今日签到

点亮在社区的每一天
去签到