forked from jsonicjs/jsonic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonic-foot.js
120 lines (95 loc) · 2.89 KB
/
jsonic-foot.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
function stringify( val, opts, depth ) {
depth++
if( null == val ) return 'null';
var type = Object.prototype.toString.call(val).charAt(8);
if( 'F' === type && !opts.showfunc ) return null;
// WARNING: output may not be jsonically parsable!
if( opts.custom ) {
if( val.hasOwnProperty('toString') ) {
return val.toString()
}
else if( val.hasOwnProperty('inspect') ) {
return val.inspect()
}
}
var out, i = 0, j, k;
if( 'N' === type ) {
return isNaN(val) ? 'null' : val.toString();
}
else if( 'O' === type ) {
out = []
if( depth <= opts.depth ) {
j = 0
for( i in val ) {
if( j >= opts.maxitems ) break;
var pass = true
for( k = 0; k < opts.exclude.length && pass; k++ ) {
pass = !~i.indexOf(opts.exclude[k])
}
pass = pass && !opts.omit[i]
var str = stringify(val[i],opts,depth)
if( null != str && pass ) {
var n = i.match(/^[a-zA-Z0-9_$]+$/) ? i : JSON.stringify(i)
out.push( n+':'+str )
j++
}
}
}
return '{'+out.join(',')+'}'
}
else if( 'A' === type ) {
out = []
if( depth <= opts.depth ) {
for( ; i < val.length && i < opts.maxitems; i++ ) {
var str = stringify(val[i],opts,depth)
if( null != str ) {
out.push( str )
}
}
}
return '['+out.join(',')+']'
}
else {
var valstr = val.toString();
if( ~" \"'\r\n\t,}]".indexOf(valstr[0]) ||
!~valstr.match(/,}]/) ||
~" \r\n\t".indexOf(valstr[valstr.length-1]))
{
valstr = "'"+valstr.replace(/'/g,"\\'")+"'"
}
return valstr;
}
}
jsonic.stringify = function( val, callopts ) {
try {
var callopts = callopts || {};
var opts = {};
opts.showfunc = callopts.showfunc || callopts.f || false;
opts.custom = callopts.custom || callopts.c || false;
opts.depth = callopts.depth || callopts.d || 3;
opts.maxitems = callopts.maxitems || callopts.mi || 11;
opts.maxchars = callopts.maxchars || callopts.mc || 111;
opts.exclude = callopts.exclude || callopts.x || ['$'];
var omit = callopts.omit || callopts.o || [];
opts.omit = {}
for( var i = 0; i < omit.length; i++ ) {
opts.omit[omit[i]] = true;
}
var str = stringify( val, opts, 0 );
str = null == str ? '' : str.substring(0,opts.maxchars);
return str;
}
catch( e ) {
return 'ERROR: jsonic.stringify: '+e+' input was: '+JSON.stringify( val )
}
}
if( typeof exports !== 'undefined' ) {
if( typeof module !== 'undefined' && module.exports ) {
exports = module.exports = jsonic
}
exports.jsonic = jsonic
}
else {
root.jsonic = jsonic
}
}).call(this);