console
function syntaxHighlight(json) {
if (typeof json != 'string') {
console.log(json)
json = JSON.stringify(json, null, 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 = '';
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';
} else if (/^[0-9]*$/.test(match)) {
cls = 'number';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
var json = [
{
"code": 200,
"type": 0,
"data": "undefined"
}
]
document.getElementById("input").onchange = function (e) {
var value = e.target.value
try {
JSON.parse(value)
} catch (e) {
document.getElementById("result").innerHTML = '格式不对'
return false
}
document.getElementById("result").innerHTML = syntaxHighlight(value)
}
document.getElementById("result").innerHTML = syntaxHighlight(json)
<textarea id="input"></textarea>
<pre id="result">
</pre>
pre {
outline: 1px solid #ccc;
padding: 5px;
margin: 5px;
}
#input {
width: calc(100% - 25px);
height: 200px;
margin: 5px;
padding: 5px;
}
.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: red;
}
.undefined {
color: gray
}