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
/*
Script: Json.js
    Simple Json parser and Stringyfier, See: <http://www.json.org/>

License:
    MIT-style license.
*/

/*
Class: Json
    Simple Json parser and Stringyfier, See: <http://www.json.org/>
*/

var Json = {

    /*
    Property: toString
        Converts an object to a string. For example to be passed in server-side scripts as a parameter.
        Only converts from $type boolean, number, string, array and object.

    Arguments:
        obj - the object to convert to string

    Returns:
        A json string or null, if the object is not encodable.

    Example:
        (start code)
        Json.toString({apple: 'red', lemon: 'yellow'}); '{"apple":"red","lemon":"yellow"}'
        (end)
    */

    toString: function(obj){
        switch($type(obj)){
            case 'boolean':
                return String(obj);
            case 'string':
                return '"' + obj.replace(Json.regExp, function(chr){
                    return Json.specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
                }) + '"';
            case 'array':
                return '[' + obj.map(Json.toString).remove(null).join(',') + ']';
            case 'object':
                var string = [];
                for(var prop in obj){
                    var val = Json.toString(obj[prop]);
                    if(val) string.push(Json.toString(prop) + ':' + val);
                }
                return '{' + string.join(',') + '}';
            case 'number':
                if (isFinite(obj)) return String(obj);
                // fall through
            case false:
                return 'null';
        }
        return null;
    },

    regExp: /([\x00-\x1f\\"])/g,
    
    specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'},

    /*
    Property: evaluate
        converts a json string to an javascript Object.

    Arguments:
        str - the string to evaluate. If its not a string, it returns null.
        secure - optionally, performs syntax check on json string. Defaults to false.

    Credits:
        Json test regexp is by Douglas Crockford <http://crockford.org>.

    Example:
        >var myObject = Json.evaluate('{"apple":"red","lemon":"yellow"}');
        >//myObject will become {apple: 'red', lemon: 'yellow'}
    */

    evaluate: function(string, secure){
        if ($type(string) != 'string' || !string.length) return null;
        if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
        return eval('(' + string + ')');
    }

};