summaryrefslogtreecommitdiff
path: root/sphinx/util/jsonimpl.py
blob: 8ccbf0cc42724c17f54edccdee610e5e95a4b7a0 (plain)
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
# -*- coding: utf-8 -*-
"""
    sphinx.util.jsonimpl
    ~~~~~~~~~~~~~~~~~~~~

    JSON serializer implementation wrapper.

    :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

import UserString

try:
    import json
    # json-py's json module has no JSONEncoder; this will raise AttributeError
    # if json-py is imported instead of the built-in json module
    JSONEncoder = json.JSONEncoder
except (ImportError, AttributeError):
    try:
        import simplejson as json
        JSONEncoder = json.JSONEncoder
    except ImportError:
        json = None
        JSONEncoder = object


class SphinxJSONEncoder(JSONEncoder):
    """JSONEncoder subclass that forces translation proxies."""
    def default(self, obj):
        if isinstance(obj, UserString.UserString):
            return unicode(obj)
        return JSONEncoder.default(self, obj)


def dump(obj, fp, *args, **kwds):
    kwds['cls'] = SphinxJSONEncoder
    return json.dump(obj, fp, *args, **kwds)

def dumps(obj, *args, **kwds):
    kwds['cls'] = SphinxJSONEncoder
    return json.dumps(obj, *args, **kwds)

def load(*args, **kwds):
    return json.load(*args, **kwds)

def loads(*args, **kwds):
    return json.loads(*args, **kwds)