1
2
3
4
5
6
7
8
9
10
11
12
13
14 import json as _json
15 import re
16
18 if isinstance(ob, dict):
19 result = {}
20 for k, v in ob.iteritems():
21 result[str(k)] = _recursiveCaster(v)
22 return result
23 elif isinstance(ob, list):
24 return [_recursiveCaster(x) for x in ob]
25 elif isinstance(ob, unicode):
26 return str(ob)
27 else:
28 return ob
29
30
32 """
33 Casts all unicode objects as strings. This is necessary until Zope is less
34 stupid.
35 """
39
41 """A simple class that represents a JavaScript literal that should not be JSON encoded."""
44
47
49 """A simple class that represents a JavaScript Regex literal that should not be JSON encoded."""
51 return '/' + self.value + '/'
52
54 """A JavaScript encoder based on JSON. It encodes like normal JSON except it passes JavaScript objects un-encoded."""
55
56 _js_start = '__js_start__'
57 _js_end = '__js_end__'
58 _js_re = re.compile(r'\["%s", (.*?), "%s"\]' % (_js_start, _js_end))
59
65
67
68
69 def fix(matchobj):
70 return _json.loads(matchobj.group(1))
71
72 return self._js_re.sub(fix, jsonstr)
73
76
77 -def json(value, **kw):
78 """
79 Serialize C{value} into a JSON string.
80
81 If C{value} is callable, a decorated version of C{value} that serializes its
82 return value will be returned.
83
84 >>> value = (dict(a=1L), u"123", 123)
85 >>> print json(value)
86 [{"a": 1}, "123", 123]
87 >>> @json
88 ... def f():
89 ... return value
90 ...
91 >>> print f()
92 [{"a": 1}, "123", 123]
93
94 @param value: An object to be serialized
95 @type value: dict, list, tuple, str, etc. or callable
96 @return: The JSON representation of C{value} or a decorated function
97 @rtype: str, func
98 """
99 if callable(value):
100
101 def inner(*args, **kwargs):
102 return _json.dumps(value(*args, **kwargs))
103
104 inner.__name__ = value.__name__
105 inner.__dict__.update(value.__dict__)
106 inner.__doc__ = value.__doc__
107 return inner
108 else:
109
110 return _json.dumps(value, **kw)
111
113 """A JavaScript encoder based on JSON. It encodes like normal JSON except it passes JavaScript objects un-encoded."""
114 return json(data, cls=JavaScriptEncoder)
115
117 """
118 Create the Python object represented by the JSON string C{value}.
119
120 >>> jsonstr = '[{"a": 1}, "123", 123]'
121 >>> print unjson(jsonstr)
122 [{'a': 1}, '123', 123]
123
124 @param value: A JSON string
125 @type value: str
126 @return: The object represented by C{value}
127 """
128 if 'cls' not in kw:
129 kw['cls'] = StringifyingDecoder
130 return _json.loads(value, **kw)
131