/* 方法1:设置textarea合适的宽高 */
#jsonTextarea {
float: left;
margin-right: 20px;
width: 40%;
height: 70vh;
outline: none;
padding: 5px;
}
/* 方法2:自定义高亮样式 */
#jsonPre {
float: left;
width: 40%;
height: 70vh;
outline: 1px solid #ccc;
padding: 5px;
overflow: scroll;
}
.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: red;
}
var data ='[{"name":"黑子","sex":"男","Age":25,"hobby":["篮球","跑步","看电影","王者荣耀"],"normal":true},{"name":"张三","sex":"男","Age":25,"hobby":["上天","入地"],"normal":false}]';
// 方法1:textarea + JSON.stringify
function parse1(str) {
return JSON.stringify(JSON.parse(str), null, "\t");
}
$('#jsonTextarea').text(parse1(data));
// 方法2:pre + JSON.stringify
function parse2(str) {
// 设置缩进为2个空格
str = JSON.stringify(JSON.parse(str), null, 2);
str = str
.replace(/&/g, '&')
.replace(/
.replace(/>/g, '>');
return str.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function(match) {
var 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';
}
return '' + match + '';
});
}
$('#jsonPre').html(parse2(data));
一键复制
编辑
Web IDE
原始数据
按行查看
历史