-
Notifications
You must be signed in to change notification settings - Fork 0
/
Toys.js
executable file
·62 lines (60 loc) · 1.32 KB
/
Toys.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
62
/**
* Make JSON visualization on browser
*
* Based on `JSON.stringify`(https://msdn.microsoft.com/library/cc836459(v=vs.94).aspx)
*
* Example:
* var obj = {
num: 1234,
str: 'string',
arr: [1,2,3,4],
obj:{
name: 'tom',
age: 10,
like: ['water','caffee']
}
};
*
* jsonViewOutput(syntaxHighlight(JSON.stringify(obj,undefined,4)));
*
* Result:
* {
"num": 1234,
"str": "string",
"arr": [
1,
2,
3,
4
],
"obj": {
"name": "tom",
"age": 10,
"like": [
"water",
"caffee"
]
}
}
*/
function jsonViewOutput(inp){
document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}
function syntaxHighlight(json){
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>';
});
}