-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathJSONPretty.jsx
72 lines (63 loc) · 2.4 KB
/
JSONPretty.jsx
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
65
66
67
68
69
70
71
72
/* eslint-disable no-unused-vars */
var React = require('react');
/* eslint-enable no-unused-vars */
var createReactClass = require('create-react-class');
module.exports = createReactClass({
// 格式化函数
_replace: function (match, ind, key, val, tra) {
var spanEnd = '</span>';
var keySpan = '<span class=json-key>';
var valSpan = '<span class=json-value>';
var strSpan = '<span class=json-string>';
var booSpan = '<span class=json-boolean>';
var sps = ind || '';
if (key) {
sps = sps + '"' + keySpan + key.replace(/^"|":\s$/g, '')+ spanEnd + '": ';
}
if (val) {
if (val === 'true' || val === 'false') {
sps = sps + booSpan + val + spanEnd;
}
else {
sps = sps + (val[0] == '"' ? strSpan : valSpan) + val + spanEnd;
}
}
return sps + (tra || '');
},
// JSON =》 HTML转换器
_pretty: function (obj, replacer, space) {
// 逐行匹配,列举:“key”: "value" | "key": value | "key": [ | "key": { | "key": [],| "Key": {},
var regLine = /^( *)("[^"]+": )?("[^"]*"|[\w.+-]*)?([,[{]|\[\s*\],?|\{\s*\},?)?$/mg;
var text = JSON.stringify(obj, typeof replacer === 'function' ? replacer : null, isNaN(space) ? 2 : space);
if (!text) {
return text;
}
return text.replace(/&/g, '&').replace(/\\"([^,])/g, '\\"$1')
.replace(/</g, '<').replace(/>/g, '>')
.replace(regLine, this._replace);
},
render: function () {
// See https://facebook.github.io/react/warnings/unknown-prop.html
var { json, replacer, space, className, themeClassName, ...rest } = this.props;
themeClassName = themeClassName ? themeClassName.trim() : themeClassName;
className = className ? className.trim() : className;
var themeClassNameFinal = themeClassName || 'json-pretty';
var classNameFinal = className ? (className + ' ' + themeClassNameFinal) : themeClassNameFinal;
if (typeof json === 'string') {
try {
json = JSON.parse(json);
}
catch (e) {
console.error('The string is not a valid json data!', e);
return(
<pre {...rest} className={classNameFinal || 'json-pretty'} dangerouslySetInnerHTML={{__html: json}}>
</pre>
);
}
}
return (
<pre {...rest} className={classNameFinal || 'json-pretty'} dangerouslySetInnerHTML={{__html: this._pretty(json, replacer, +space)}}>
</pre>
);
}
});