html中展示json資料結構
附原始碼:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
pre {
outline: 1px solid #ccc;
padding: 5px;
left: 50%;
position: absolute;
right: 0;
}
.content {
position: fixed;
left: 10%;
}
.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: red;
}
</style>
</head>
<body>
<pre id="result"></pre>
</body>
<script>
renderData(json格式的資料,
"後臺資料地址");
function renderData(options, url) {
var inData = {};
inData.controller = "";
inData.action = "";
inData.version = "";
inData.token = "";
inData.options = options;
$.ajax({
type : "POST",
url : url,
dataType : "json",
contentType : "application/json;charset=UTF-8",
data : JSON.stringify(inData),
success : function(data) {
$('#result').html(syntaxHighlight(data));
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
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) {
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 '<span class="' + cls + '">' + match + '</span>';
});
}
</script>
</html>