a96356ccbacb311af5121ae40a766a4689f3a0cf
[django-ssify.git] / ssify / serializers.py
1 import json
2 from .variables import SsiVariable, SsiExpect
3
4
5 def _json_default(o):
6     if isinstance(o, SsiVariable):
7         return {'__var__': o.name}
8     if isinstance(o, SsiExpect):
9         return {'__expect__': o.name}
10     raise TypeError(o, 'not JSON serializable')
11
12
13 def _json_obj_hook(obj):
14     if obj.keys() == ['__var__']:
15         return SsiVariable(name=obj['__var__'])
16     if obj.keys() == ['__expect__']:
17         return SsiExpect(obj['__expect__'])
18     return obj
19
20
21 def json_encode(obj, **kwargs):
22     return json.JSONEncoder(
23         default=_json_default,
24         separators=(',', ':'),
25         **kwargs).encode(obj)
26
27
28 def json_decode(data, **kwargs):
29     return json.loads(data, object_hook=_json_obj_hook, **kwargs)