Skip to content

Commit 496e714

Browse files
committed
Complete refactor, support for native JSON.stringify
1 parent ddb6167 commit 496e714

File tree

5 files changed

+227
-161
lines changed

5 files changed

+227
-161
lines changed

jquery-1.3.2.min.js

Lines changed: 19 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

jquery.json.js

Lines changed: 130 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -5,143 +5,122 @@
55
* This document is licensed as free software under the terms of the
66
* MIT License: http://www.opensource.org/licenses/mit-license.php
77
*
8-
* Brantley Harris technically wrote this plugin, but it is based somewhat
9-
* on the JSON.org website's http://www.json.org/json2.js, which proclaims:
8+
* Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
9+
* website's http://www.json.org/json2.js, which proclaims:
1010
* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
11-
* I uphold. I really just cleaned it up.
11+
* I uphold.
1212
*
13-
* It is also based heavily on MochiKit's serializeJSON, which is
14-
* copywrited 2005 by Bob Ippolito.
13+
* It is also influenced heavily by MochiKit's serializeJSON, which is
14+
* copyrighted 2005 by Bob Ippolito.
1515
*/
1616

17-
(function($) {
18-
function toIntegersAtLease(n)
19-
// Format integers to have at least two digits.
20-
{
21-
return n < 10 ? '0' + n : n;
22-
}
17+
(function($) {
18+
/** jQuery.toJSON( json-serializble )
19+
Converts the given argument into a JSON respresentation.
2320
24-
Date.prototype.toJSON = function(date)
25-
// Yes, it polutes the Date namespace, but we'll allow it here, as
26-
// it's damned usefull.
27-
{
28-
return this.getUTCFullYear() + '-' +
29-
toIntegersAtLease(this.getUTCMonth()) + '-' +
30-
toIntegersAtLease(this.getUTCDate());
31-
};
21+
If an object has a "toJSON" function, that will be used to get the representation.
22+
Non-integer/string keys are skipped in the object, as are keys that point to a function.
3223
33-
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
34-
var meta = { // table of character substitutions
35-
'\b': '\\b',
36-
'\t': '\\t',
37-
'\n': '\\n',
38-
'\f': '\\f',
39-
'\r': '\\r',
40-
'"' : '\\"',
41-
'\\': '\\\\'
42-
};
43-
44-
$.quoteString = function(string)
45-
// Places quotes around a string, inteligently.
46-
// If the string contains no control characters, no quote characters, and no
47-
// backslash characters, then we can safely slap some quotes around it.
48-
// Otherwise we must also replace the offending characters with safe escape
49-
// sequences.
24+
json-serializble:
25+
The *thing* to be converted.
26+
**/
27+
$.toJSON = function(o)
5028
{
51-
if (escapeable.test(string))
52-
{
53-
return '"' + string.replace(escapeable, function (a)
54-
{
55-
var c = meta[a];
56-
if (typeof c === 'string') {
57-
return c;
58-
}
59-
c = a.charCodeAt();
60-
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
61-
}) + '"';
62-
}
63-
return '"' + string + '"';
64-
};
65-
66-
$.toJSON = function(o, compact)
67-
{
68-
var type = typeof(o);
29+
if (JSON && JSON.stringify)
30+
return JSON.stringify(o);
6931

70-
if (type == "undefined")
71-
return "undefined";
72-
else if (type == "number" || type == "boolean")
73-
return o + "";
74-
else if (o === null)
32+
var type = typeof(o);
33+
34+
if (o === null)
7535
return "null";
36+
37+
if (type == "undefined")
38+
return undefined;
7639

77-
// Is it a string?
78-
if (type == "string")
79-
{
40+
if (type == "number" || type == "boolean")
41+
return o + "";
42+
43+
if (type == "string")
8044
return $.quoteString(o);
81-
}
82-
83-
// Does it have a .toJSON function?
84-
if (type == "object" && typeof o.toJSON == "function")
85-
return o.toJSON(compact);
86-
87-
// Is it an array?
88-
if (type != "function" && typeof(o.length) == "number")
45+
46+
if (type == 'object')
8947
{
90-
var ret = [];
91-
for (var i = 0; i < o.length; i++) {
92-
ret.push( $.toJSON(o[i], compact) );
48+
if (typeof o.toJSON == "function")
49+
return $.toJSON( o.toJSON() );
50+
51+
if (o.constructor === Date)
52+
{
53+
var month = o.getUTCMonth() + 1;
54+
if (month < 10) month = '0' + month;
55+
56+
var day = o.getUTCDate();
57+
if (day < 10) day = '0' + day;
58+
59+
var year = o.getUTCFullYear();
60+
61+
var hours = o.getUTCHours();
62+
if (hours < 10) hours = '0' + hours;
63+
64+
var minutes = o.getUTCMinutes();
65+
if (minutes < 10) minutes = '0' + minutes;
66+
67+
var seconds = o.getUTCSeconds();
68+
if (seconds < 10) seconds = '0' + seconds;
69+
70+
var milli = o.getUTCMilliseconds();
71+
if (milli < 100) milli = '0' + milli;
72+
if (milli < 10) milli = '0' + milli;
73+
74+
return '"' + year + '-' + month + '-' + day + 'T' +
75+
hours + ':' + minutes + ':' + seconds +
76+
'.' + milli + 'Z"';
9377
}
94-
if (compact)
78+
79+
if (o.constructor === Array)
80+
{
81+
var ret = [];
82+
for (var i = 0; i < o.length; i++)
83+
ret.push( $.toJSON(o[i]) );
84+
9585
return "[" + ret.join(",") + "]";
96-
else
97-
return "[" + ret.join(", ") + "]";
98-
}
99-
100-
// If it's a function, we have to warn somebody!
101-
if (type == "function") {
102-
throw new TypeError("Unable to convert object of type 'function' to json.");
103-
}
86+
}
10487

105-
// It's probably an object, then.
106-
var ret = [];
107-
for (var k in o) {
108-
var name;
109-
type = typeof(k);
88+
var pairs = [];
89+
for (var k in o) {
90+
var name;
91+
var type = typeof k;
92+
93+
if (type == "number")
94+
name = '"' + k + '"';
95+
else if (type == "string")
96+
name = $.quoteString(k);
97+
else
98+
continue; //skip non-string or number keys
11099

111-
if (type == "number")
112-
name = '"' + k + '"';
113-
else if (type == "string")
114-
name = $.quoteString(k);
115-
else
116-
continue; //skip non-string or number keys
100+
if (typeof o[k] == "function")
101+
continue; //skip pairs where the value is a function.
117102

118-
var val = $.toJSON(o[k], compact);
119-
if (typeof(val) != "string") {
120-
// skip non-serializable values
121-
continue;
122-
}
103+
var val = $.toJSON(o[k]);
123104

124-
if (compact)
125-
ret.push(name + ":" + val);
126-
else
127-
ret.push(name + ": " + val);
105+
pairs.push(name + ":" + val);
106+
}
107+
108+
return "{" + pairs.join(", ") + "}";
128109
}
129-
return "{" + ret.join(", ") + "}";
130-
};
131-
132-
$.compactJSON = function(o)
133-
{
134-
return $.toJSON(o, true);
135-
};
136-
110+
}
111+
112+
/** jQuery.evalJSON(src)
113+
Evaluates a given piece of json source.
114+
**/
137115
$.evalJSON = function(src)
138-
// Evals JSON that we know to be safe.
139116
{
140117
return eval("(" + src + ")");
141-
};
118+
}
142119

120+
/** jQuery.secureEvalJSON(src)
121+
Evals JSON in a way that is *more* secure.
122+
**/
143123
$.secureEvalJSON = function(src)
144-
// Evals JSON in a way that is *more* secure.
145124
{
146125
var filtered = src;
147126
filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
@@ -153,4 +132,42 @@
153132
else
154133
throw new SyntaxError("Error parsing JSON, source is not valid.");
155134
};
135+
136+
/** jQuery.quoteString(string)
137+
Returns a string-repr of a string, escaping quotes intelligently.
138+
Mostly a support function for toJSON.
139+
140+
Examples:
141+
>>> jQuery.quoteString("apple")
142+
"apple"
143+
144+
>>> jQuery.quoteString('"Where are we going?", she asked.')
145+
"\"Where are we going?\", she asked."
146+
**/
147+
$.quoteString = function(string)
148+
{
149+
if (_escapeable.test(string))
150+
{
151+
return '"' + string.replace(_escapeable, function (a)
152+
{
153+
var c = _meta[a];
154+
if (typeof c === 'string') return c;
155+
c = a.charCodeAt();
156+
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
157+
}) + '"'
158+
}
159+
return '"' + string + '"';
160+
}
161+
162+
var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
163+
164+
var _meta = {
165+
'\b': '\\b',
166+
'\t': '\\t',
167+
'\n': '\\n',
168+
'\f': '\\f',
169+
'\r': '\\r',
170+
'"' : '\\"',
171+
'\\': '\\\\'
172+
}
156173
})(jQuery);

jquery.json.min.js

Lines changed: 27 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,32 @@
11

2-
(function($){function toIntegersAtLease(n)
3-
{return n<10?'0'+n:n;}
4-
Date.prototype.toJSON=function(date)
5-
{return this.getUTCFullYear()+'-'+
6-
toIntegersAtLease(this.getUTCMonth())+'-'+
7-
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
8-
{if(escapeable.test(string))
9-
{return'"'+string.replace(escapeable,function(a)
10-
{var c=meta[a];if(typeof c==='string'){return c;}
11-
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
12-
return'"'+string+'"';};$.toJSON=function(o,compact)
13-
{var type=typeof(o);if(type=="undefined")
14-
return"undefined";else if(type=="number"||type=="boolean")
15-
return o+"";else if(o===null)
16-
return"null";if(type=="string")
17-
{return $.quoteString(o);}
18-
if(type=="object"&&typeof o.toJSON=="function")
19-
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
20-
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
21-
if(compact)
22-
return"["+ret.join(",")+"]";else
23-
return"["+ret.join(", ")+"]";}
24-
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
25-
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
2+
(function($){$.toJSON=function(o)
3+
{if(JSON&&JSON.stringify)
4+
return JSON.stringify(o);var type=typeof(o);if(o===null)
5+
return"null";if(type=="undefined")
6+
return undefined;if(type=="number"||type=="boolean")
7+
return o+"";if(type=="string")
8+
return $.quoteString(o);if(type=='object')
9+
{if(typeof o.toJSON=="function")
10+
return $.toJSON(o.toJSON());if(o.constructor===Date)
11+
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
12+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
13+
if(o.constructor===Array)
14+
{var ret=[];for(var i=0;i<o.length;i++)
15+
ret.push($.toJSON(o[i]));return"["+ret.join(",")+"]";}
16+
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
2617
name='"'+k+'"';else if(type=="string")
2718
name=$.quoteString(k);else
28-
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
29-
if(compact)
30-
ret.push(name+":"+val);else
31-
ret.push(name+": "+val);}
32-
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
33-
{return $.toJSON(o,true);};$.evalJSON=function(src)
34-
{return eval("("+src+")");};$.secureEvalJSON=function(src)
19+
continue;if(typeof o[k]=="function")
20+
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
21+
return"{"+pairs.join(", ")+"}";}}
22+
$.evalJSON=function(src)
23+
{return eval("("+src+")");}
24+
$.secureEvalJSON=function(src)
3525
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
3626
return eval("("+src+")");else
37-
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);
27+
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
28+
{if(_escapeable.test(string))
29+
{return'"'+string.replace(_escapeable,function(a)
30+
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"'}
31+
return'"'+string+'"';}
32+
var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'}})(jQuery);

0 commit comments

Comments
 (0)