-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSON_print.html
64 lines (53 loc) · 1.83 KB
/
JSON_print.html
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
63
64
<style>
body{
background: #efefef;
}
pre {
background-color: ghostwhite;
border: 1px solid silver;
padding: 10px 20px;
margin: 20px;
border-radius: 4px;
width: 25%;
margin-left: auto;
margin-right: auto;
}
</style>
<script>
/**
* Pretty Print JSON Objects.
* Inspired by http://jsfiddle.net/unLSJ/
*
* @return {string} html string of the formatted JS object
* @example: var obj = {"foo":"bar"}; obj.prettyPrint();
*/
Object.prototype.prettyPrint = function(){
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
var replacer = function(match, pIndent, pKey, pVal, pEnd) {
var key = '<span class="json-key" style="color: brown">',
val = '<span class="json-value" style="color: navy">',
str = '<span class="json-string" style="color: olive">',
r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal)
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
return r + (pEnd || '');
};
return JSON.stringify(this, null, 3)
.replace(/&/g, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.replace(jsonLine, replacer);
}
var account = { active: true, codes: [48348, 28923, 39080], city: "London" };
var planets = [{ name: 'Earth', order: 3, stats: { life: true, mass: 5.9736 * Math.pow(10, 24) } }, { name: 'Saturn', order: 6, stats: { life: null, mass: 568.46 * Math.pow(10, 24) } }];
</script>
<html>
<pre><code id=acct></code></pre>
<pre><code id=planets></code></pre>
<pre><code id=data></code></pre>
<script>
document.getElementById('acct').innerHTML = account.prettyPrint();
document.getElementById('planets').innerHTML = planets.prettyPrint();
</script>
</html>