pfunk.utils.json_utils
View Source
import inspect from faunadb.objects import Ref from valley.utils.json_utils import ValleyEncoder class PFunkEncoder(ValleyEncoder): show_type = False def default(self, obj): if isinstance(obj, Ref): obj_dict = {'id': obj.id(), 'collection': obj.collection().id()} if self.show_type: obj_dict['_type'] = '{}.{}'.format(inspect.getmodule(obj).__name__, obj.__class__.__name__) return obj_dict if hasattr(obj, 'get_collection_name'): if obj._lazied: obj = obj._get(obj.ref.id()) try: return super(PFunkEncoder, self).default(obj) except AttributeError: return str(obj)
View Source
class PFunkEncoder(ValleyEncoder): show_type = False def default(self, obj): if isinstance(obj, Ref): obj_dict = {'id': obj.id(), 'collection': obj.collection().id()} if self.show_type: obj_dict['_type'] = '{}.{}'.format(inspect.getmodule(obj).__name__, obj.__class__.__name__) return obj_dict if hasattr(obj, 'get_collection_name'): if obj._lazied: obj = obj._get(obj.ref.id()) try: return super(PFunkEncoder, self).default(obj) except AttributeError: return str(obj)
Extensible JSON http://json.org encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str | string | +-------------------+---------------+ | int, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
.default()
method with another method that returns a serializable
object for o
if possible, otherwise it should call the superclass
implementation (to raise TypeError
).
View Source
def default(self, obj): if isinstance(obj, Ref): obj_dict = {'id': obj.id(), 'collection': obj.collection().id()} if self.show_type: obj_dict['_type'] = '{}.{}'.format(inspect.getmodule(obj).__name__, obj.__class__.__name__) return obj_dict if hasattr(obj, 'get_collection_name'): if obj._lazied: obj = obj._get(obj.ref.id()) try: return super(PFunkEncoder, self).default(obj) except AttributeError: return str(obj)
Implement this method in a subclass such that it returns
a serializable object for o
, or calls the base implementation
(to raise a TypeError
).
For example, to support arbitrary iterators, you could implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return JSONEncoder.default(self, o)
Inherited Members
- json.encoder.JSONEncoder
- JSONEncoder
- item_separator
- key_separator
- encode
- iterencode