-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonHighlighter.js
61 lines (51 loc) · 1.99 KB
/
jsonHighlighter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* JSON Highlighter : Small JSON highlighter for your webpage.
* http://cope.github.io/jsonHighlighterJS/
*
* Licensed under the MIT licenses.
* (if anyone knows how to change the license on github, please let me know so that I can unlicense it)
*
* Inspired by (read: stolen from) http://stackoverflow.com/a/7220510
* Therefore, all credit goes to Pumbaa80 (http://stackoverflow.com/users/27862/pumbaa80)
*
*/
var cope = {
Highlighter: {
cssString: "color: darkgreen;",
cssNumber: "color: darkorange;",
cssBoolean: "color: blue;",
cssNull: "color: magenta;",
cssKey: "color: red;"
}
};
cope.Highlighter.convertCssStyle = function (reg) {
return /:$/.test(reg) ? cope.Highlighter.cssKey : cope.Highlighter.cssString;
};
cope.Highlighter.convertNonCssStyle = function (reg) {
if (/true|false/.test(reg)) return cope.Highlighter.cssBoolean;
if (/null/.test(reg)) return cope.Highlighter.cssNull;
return cope.Highlighter.cssNumber;
};
cope.Highlighter.convertStyle = function (reg) {
return /^"/.test(reg) ? cope.Highlighter.convertCssStyle(reg) : cope.Highlighter.convertNonCssStyle(reg);
};
cope.Highlighter.match = function (reg) {
return "<span style=\"" + cope.Highlighter.convertStyle(reg) + "\">" + reg + "</span>";
};
cope.Highlighter.fixOptions = function (options) {
options.indent = options.indent || 2;
options.useTabs = true === options.useTabs;
return options;
};
cope.Highlighter.fixJSON = function (json) {
return (typeof json === "string") ? JSON.parse(json) : json;
};
cope.Highlighter.highlight = function (json, options) {
json = cope.Highlighter.fixJSON(json);
options = cope.Highlighter.fixOptions(options);
var tabs = options.useTabs;
var indent = options.indent;
json = JSON.stringify(json, null, (tabs === true ? "\t" : indent));
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, cope.Highlighter.match);
};