用pre
标签渲染Json数据
const formatJSONData = (json: string) => {
// 获取补位的空格数
const getSpaces = (level: number) => {
if (level === 0) return '';
let size = level * 2, result = '';
while(size--) {
result += ' ';
}
return result;
}
let level = 0, result = '';
for(let i = 0; i < json.length; i++) {
if(json[i] == '}' || json[i] == ']') {
result += '\n' + getSpaces(--level) + json[i];
} else if(json[i] == '{' || json[i] == '[') {
result += json[i] + '\n' + getSpaces(++level);
} else if(json[i] == ',') {
result += json[i] + '\n' + getSpaces(level);
} else {
result += json[i];
}
}
return result.replace(/([{[][\t\n\s]+[{[}\]])|([}\]],?[\t\n\s]+[{[}\]])|("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
let cls = 'number', suffix = '';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
suffix = ': ';
match = match.substring(0, match.length - 1);
} else {
cls = 'string';
}
} else if (/[\t\n\s]+/.test(match)) {
return match.replace(/[\t\n\s]+/, '');
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return ['<span class="', cls, '">', match, '</span>', suffix].join('');
});
}
样式
#result {
overflow-y: scroll;
outline: 1px solid #ccc;
height: 500px;
padding: 5px;
margin: 5px;
}
#result > *:hover { background-color: rgba(230, 230, 230, 0.9); }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }