def jsonfy(obj, json_level=None, print_type=True, invertible=False, recursive=True): '''Return a JSON representation of object. Parameters ---------- obj : anything Object to be converted to JSON json_level : int Maximum JSON level allowed for the given type. print_type : bool Set to False to prevent adding the ('@type': value) pair to the resulting object. This key is used to convert the JSON object to the appropriate Python type. invertible : bool If True, the output can be converted back to an identical Python object. The default behavior is to allow approximate types, e.g., ``str`` can be converted to ``unicode``, ``tuple`` to ``list`` and so on. recursive : bool If False and json_level is respected or not set, it prevents recursive application of func:`jsonfy` to child nodes of the JSON result. ''' tt = type(obj) if json_level is not None or invertible: raise NotImplementedError # Compute the result from the converter function try: function = CONVERTERS[tt] except KeyError: function = auto_converter(tt) try: result = function(obj) except Exception as ex: msg = 'unhandled exception raised when jsonfy-ing %s object\n %s: %s' msg = msg % (type(obj), type(ex).__name__, ex) raise RuntimeError(msg) # Print type if print_type and not is_object_t(tt): try: result[u'@type'] = type2name(tt) except: pass #TODO: move recursive to converter function if recursive: if isinstance(result, dict): for k, v in result.items(): result[k] = jsonfy(v, json_level=json_level, print_type=print_type, invertible=invertible, recursive=recursive) elif isinstance(result, list): for idx, v in enumerate(result): result[idx] = jsonfy(v, json_level=json_level, print_type=print_type, invertible=invertible, recursive=recursive) return result
def __new__(cls, *args, **kwds): # If Schema() is called directly, it will choose an appropriate # constructor and initialize a subclass. if cls is Schema: if not args: raise TypeError('Schema() takes at least one positional argument (0 given)') tt = type(args[0]) # Choose the correct constructor from the type of the 1st argument if is_object_t(tt): return cls.OBJECT_SCHEMA(*args, **kwds) elif is_array_t(tt): return cls.ARRAY_SCHEMA(*args, **kwds) else: return cls.CTE_SCHEMA(*args, **kwds) # This is path is called when Schema.__new__() is called from a subclass else: return object.__new__(cls)