- uploading 1.1 in tags
[mootools.git] / Remote / Json.js
blob15baf4ac13ea92d8ce1a9c6ebff1e1cab26b1d9c
1 /*
2 Script: Json.js
3         Simple Json parser and Stringyfier, See: <http://www.json.org/>
5 License:
6         MIT-style license.
7 */
9 /*
10 Class: Json
11         Simple Json parser and Stringyfier, See: <http://www.json.org/>
14 var Json = {
16         /*
17         Property: toString
18                 Converts an object to a string, to be passed in server-side scripts as a parameter. Although its not normal usage for this class, this method can also be used to convert functions and arrays to strings.
20         Arguments:
21                 obj - the object to convert to string
23         Returns:
24                 A json string
26         Example:
27                 (start code)
28                 Json.toString({apple: 'red', lemon: 'yellow'}); '{"apple":"red","lemon":"yellow"}'
29                 (end)
30         */
32         toString: function(obj){
33                 switch($type(obj)){
34                         case 'string':
35                                 return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
36                         case 'array':
37                                 return '[' + obj.map(Json.toString).join(',') + ']';
38                         case 'object':
39                                 var string = [];
40                                 for (var property in obj) string.push(Json.toString(property) + ':' + Json.toString(obj[property]));
41                                 return '{' + string.join(',') + '}';
42                 }
43                 return String(obj);
44         },
46         /*
47         Property: evaluate
48                 converts a json string to an javascript Object.
50         Arguments:
51                 str - the string to evaluate. if its not a string, it returns false.
52                 secure - optionally, performs syntax check on json string. Defaults to false.
54         Credits:
55                 Json test regexp is by Douglas Crockford <http://crockford.org>.
57         Example:
58                 >var myObject = Json.evaluate('{"apple":"red","lemon":"yellow"}');
59                 >//myObject will become {apple: 'red', lemon: 'yellow'}
60         */
62         evaluate: function(str, secure){
63                 return (($type(str) != 'string') || (secure && !str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/))) ? false : eval('(' + str + ')');
64         }