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 """Thin abstraction layer over the different available modules for decoding
34 and encoding JSON data.
35
36 This module currently supports the following JSON modules:
37 - ``simplejson``: http://code.google.com/p/simplejson/
38 - ``cjson``: http://pypi.python.org/pypi/python-cjson
39 - ``json``: This is the version of ``simplejson`` that is bundled with the
40 Python standard library since version 2.6
41 (see http://docs.python.org/library/json.html)
42
43 The default behavior is to use ``simplejson`` if installed, and otherwise
44 fallback to the standard library module. To explicitly tell SPARQLWrapper
45 which module to use, invoke the `use()` function with the module name::
46
47 import jsonlayer
48 jsonlayer.use('cjson')
49
50 In addition to choosing one of the above modules, you can also configure
51 SPARQLWrapper to use custom decoding and encoding functions::
52
53 import jsonlayer
54 jsonlayer.use(decode=my_decode, encode=my_encode)
55
56 """
57
58 __all__ = ['decode', 'encode', 'use']
59
60 _initialized = False
61 _using = None
62 _decode = None
63 _encode = None
64
65
67 """Decode the given JSON string.
68
69 :param string: the JSON string to decode
70 :type string: basestring
71 :return: the corresponding Python data structure
72 :rtype: object
73 """
74 if not _initialized:
75 _initialize()
76 return _decode(string)
77
78
80 """Encode the given object as a JSON string.
81
82 :param obj: the Python data structure to encode
83 :type obj: object
84 :return: the corresponding JSON string
85 :rtype: basestring
86 """
87 if not _initialized:
88 _initialize()
89 return _encode(obj)
90
91
92 -def use(module=None, decode=None, encode=None):
93 """Set the JSON library that should be used, either by specifying a known
94 module name, or by providing a decode and encode function.
95
96 The modules "simplejson", "cjson", and "json" are currently supported for
97 the ``module`` parameter.
98
99 If provided, the ``decode`` parameter must be a callable that accepts a
100 JSON string and returns a corresponding Python data structure. The
101 ``encode`` callable must accept a Python data structure and return the
102 corresponding JSON string. Exceptions raised by decoding and encoding
103 should be propagated up unaltered.
104
105 :param module: the name of the JSON library module to use, or the module object itself
106 :type module: str or module
107 :param decode: a function for decoding JSON strings
108 :type decode: callable
109 :param encode: a function for encoding objects as JSON strings
110 :type encode: callable
111 """
112 global _decode, _encode, _initialized, _using
113 if module is not None:
114 if not isinstance(module, basestring):
115 module = module.__name__
116 if module not in ('cjson', 'json', 'simplejson'):
117 raise ValueError('Unsupported JSON module %s' % module)
118 _using = module
119 _initialized = False
120 else:
121 assert decode is not None and encode is not None
122 _using = 'custom'
123 _decode = decode
124 _encode = encode
125 _initialized = True
126
127
129 global _initialized
130
131 def _init_simplejson():
132 global _decode, _encode
133 import simplejson
134 _decode = lambda string, loads=simplejson.loads: loads(string)
135 _encode = lambda obj, dumps=simplejson.dumps: \
136 dumps(obj, allow_nan=False, ensure_ascii=False)
137
138 def _init_cjson():
139 global _decode, _encode
140 import cjson
141 _decode = lambda string, decode=cjson.decode: decode(string)
142 _encode = lambda obj, encode=cjson.encode: encode(obj)
143
144 def _init_stdlib():
145 global _decode, _encode
146 json = __import__('json', {}, {})
147 _decode = lambda string, loads=json.loads: loads(string)
148 _encode = lambda obj, dumps=json.dumps: \
149 dumps(obj, allow_nan=False, ensure_ascii=False)
150
151 if _using == 'simplejson':
152 _init_simplejson()
153 elif _using == 'cjson':
154 _init_cjson()
155 elif _using == 'json':
156 _init_stdlib()
157 elif _using != 'custom':
158 try:
159 _init_simplejson()
160 except ImportError:
161 _init_stdlib()
162 _initialized = True
163