.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: red;
}
function removeQuotesAndColon(str){
let reg = new RegExp('\"|:',"g");
let result = str.replace(reg, "");
return result;
}
function humpToStr(val){
let newStr = removeQuotesAndColon(val);
let str = newStr.replace(/([A-Z])/g," $1")
let result = str.substr(0,1).toUpperCase() + str.substr(1);
return result.trim() + ":";
}
function parseJsonData(jsonData) {
if (null == jsonData){
return "";
}
let reg = new RegExp(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,"g");
jsonData = JSON.stringify(JSON.parse(jsonData), null, 2);
jsonData = jsonData
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
return jsonData.replace(reg, function(match) {
let cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
match = humpToStr(match)
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
效果图
测试数据:var data = ‘[{“date”: “2022/04/08”, “Text”: “text”, “number”: 22, “flag”: true,“HobbyList”:[“看电影”,“王者荣耀”]}, {“date”: “2022/04/08”, “Text”: “text”, “number”: 22, “flag”: true,“HobbyList”:[“看电影”,“王者荣耀”]}]’;
|