要在頁面中顯示美化JSON格式化

需求場景:有時(shí)候我們需要將json數(shù)據(jù)直接顯示在頁面上(比如在做一個(gè)接口測試的項(xiàng)目,需要將接口返回的結(jié)果直接展示),但是如果直接顯示字符串,不方便查看。需要格式化一下。
倆種解決方法,第2種使用插件包比較方便。

解決方法1:

其實(shí)JSON.stringify本身就可以將JSON格式化,直接用法就是:

JSON.stringify(res, null, 2); //res是要JSON化的對象,2是spacing

詳細(xì)優(yōu)化:

<template><div><pre id="result" ref="preRef" /></div></template>
// 在
<script>
export default {
  name:"Index",
  data(){reutrn{
 jsonData : {
            "msg": "success", "code": 200,"data": [{"id": 0, "door_name": "1",   },{"id": 1, "door_name": "2",   },], "count": 2
        };
}},
  mounted() {
    this.$refs.preRef.innerHTML = this.syntaxHighlight(this.jsonData)
  },
  methods: {
    syntaxHighlight(str) {
      if (typeof str !== 'string') {
        str = JSON.stringify(str, undefined, 2)
      }
      str = str
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
      return str.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
        var cls = 'number'
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            cls = 'key'
          } else {
            cls = 'string'
          }
        } else if (/true|false/.test(match)) {
          cls = 'boolean'
        } else if (/null/.test(match)) {
          cls = 'null'
        }
        return '<span class="' + cls + '">' + match + '</span>'
      })
    },
}
}
</script>
<style lang="scss" scoped>
    ::v-deep{
        #result {
            outline: 1px solid #ccc;
            padding: 5px;
            margin: 5px;
        }
        .string { color: green; }
        .number { color: darkorange; }
        .boolean { color: blue; }
        .null { color: magenta; }
        .key { color: red; }
    }

</style>

效果展示:


image.png

解決方法2:安裝vue-json-viewer插件

npm安裝一下

npm install vue-json-viewer --save

代碼實(shí)現(xiàn),掛載vue里面

import Vue from 'vue'
import JsonViewer from 'vue-json-viewer'
 
// Import JsonViewer as a Vue.js plugin
Vue.use(JsonViewer)
// or 
// components: {JsonViewer}

在template里面加入如下一種: 其中jsonData必須是json類型的數(shù)據(jù)。

<json-viewer :value="jsonData"></json-viewer>
 
<hr />
 
<json-viewer
  :value="jsonData"
  :expand-depth=5
  copyable
  boxed
  sort></json-viewer>

效果展示:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容