json.cn our development process, often used to display formatting JSON
tools URL string, then how to display the same style of writing in their own front-end interface, after formatting JSON
string 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> <span class="' + cls + '">' + match + ' </span>';
} else {
return '<span class="' + cls + '">' + match + '</span>';
}
}).replace("}", "<br>}");
},