前端如何优雅地显示 JSON

json.cn 是我们开发过程中,经常用来格式化显示 JSON 字符串的工具网址,那么如何在自己编写的前端界面显示同样风格的、格式化之后 JSON 字符串呢?

网上流传的版本显示出来效果并不尽如人意,因此小改了一下。

代码如下

<pre>{{syntaxHighlight(data)}}</pre>

CSS

pre {padding: 5px; margin: 5px; }
    .string { color: #3ab54a; font-weight: bold;}
    .number { color: #25aae2; font-weight: bold;}
    .boolean { color: #f98280; font-weight: bold;}
    .null { color: magenta; font-weight: bold;}
    .key { color: #92278f;font-weight: bold; }

JS

syntaxHighlight(json) {
                if (typeof json !== 'string') {
                    json = JSON.stringify(json, undefined, 4);
                }
                json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
                return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
                    let 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';
                    }
                    if(cls == 'key') {
                        return '<br>&nbsp;&nbsp;&nbsp;&nbsp;<span class="' + cls + '">' + match + '&nbsp;</span>';
                    } else {
                        return '<span class="' + cls + '">' + match + '</span>';
                    }
                }).replace("}", "<br>}");
            },

参考资料

简单一招实现json数据可视化

发布了77 篇原创文章 · 获赞 50 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/chen_kkw/article/details/86737745