Skip to content

Instantly share code, notes, and snippets.

@caracal7
Forked from twilson63/json-syntax-highlighter.js
Last active August 27, 2019 10:19
Show Gist options
  • Save caracal7/3dd33d8f4e7c90cc44ebe4b25c11c891 to your computer and use it in GitHub Desktop.
Save caracal7/3dd33d8f4e7c90cc44ebe4b25c11c891 to your computer and use it in GitHub Desktop.
Javascript JSON syntax highlight
const isISODate = date => new Date(date) !== "Invalid Date" && !isNaN(new Date(date)) && date == new Date(date).toISOString();
const syntaxHighlight = json => {
json = JSON.stringify(json, null, ' ')
json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
var result = 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';
match = match.substring(1, match.length-2);
} else {
if (/"[\d]+"/.test(match)) cls = 'number';
else cls = 'string';
match = match.substring(1, match.length-1);
if(isISODate(match)) cls = 'date';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
if (cls === 'key') return '<span class="' + cls + '">' + match + '</span>:';
else if (cls === 'string') return '"<span class="' + cls + '">' + match + '</span>"';
else return '<span class="' + cls + '">' + match + '</span>';
});
return result;
}
.key {
color:#ddd;
}
.string {
color:rgb(46, 204, 113);
}
.number {
color:lightblue;
}
.boolean {
color:yellow;
}
.date {
color:Brown;
}
.null {
color:gray;
}
.version {
color:blue;
}
.container {
color: gray;
white-space:pre;
user-select:text;
-webkit-user-select:text;
font-family:DejavuSans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment