How gracefully the front display JSON

json.cn our development process, often used to display formatting JSONtools URL string, then how to display the same style of writing in their own front-end interface, after formatting JSONstring it?

Circulated on the Internet version of the displayed results were not satisfactory, and therefore little changed a bit.

code show as below

<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>}");
            },

Reference material

Simple realize a trick data visualization json

Published 77 original articles · won praise 50 · views 50000 +

Guess you like

Origin blog.csdn.net/chen_kkw/article/details/86737745