Package SPARQLWrapper :: Module jsonlayer
[hide private]
[frames] | no frames]

Source Code for Module SPARQLWrapper.jsonlayer

  1  # -*- coding: utf-8 -*- 
  2  # 
  3  # Copyright (C) 2009 Christopher Lenz 
  4  # All rights reserved. 
  5  # 
  6   
  7  # Redistribution and use in source and binary forms, with or without 
  8  # modification, are permitted provided that the following conditions 
  9  # are met: 
 10   
 11  # 1. Redistributions of source code must retain the above copyright 
 12  # notice, this list of conditions and the following disclaimer. 
 13  # 2. Redistributions in binary form must reproduce the above copyright 
 14  # notice, this list of conditions and the following disclaimer in 
 15  # the documentation and/or other materials provided with the 
 16  # distribution. 
 17  # 3. The name of the author may not be used to endorse or promote 
 18  # products derived from this software without specific prior 
 19  # written permission. 
 20   
 21  # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS 
 22  # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 23  # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 24  # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 
 25  # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 26  # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
 27  # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 28  # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
 29  # IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
 30  # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN 
 31  # IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 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   
66 -def decode(string):
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
79 -def encode(obj):
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
128 -def _initialize():
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