Skip to content

Instantly share code, notes, and snippets.

@necessary129
Created June 12, 2016 08:52
Show Gist options
  • Save necessary129/42df6085a26b29272733866c3a5851a3 to your computer and use it in GitHub Desktop.
Save necessary129/42df6085a26b29272733866c3a5851a3 to your computer and use it in GitHub Desktop.
Modular JSON Encoder. (With a register method for custom types)
# Copyright (c) 2016 Muhammed Shamil K
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import json
"""\
This module contains a Modular JSON Encoder useful
for encoding custom Python objects and types. Simply
call it's `register_adapter` method and then give it as
the `cls` argment to `json.dump` or `json.dumps`. Like this:
>>> from decimal import Decimal
>>> ModularEncoder.register_adapter(Decimal, lambda dec: float(dec))
>>> obj = {"something": Decimal(0.5746)}
>>> json.dumps(obj, cls=ModularEncoder)
"""
class ModularEncoder(json.JSONEncoder):
"""\
Custom JSON Encoder.
Custom types can be added to the Encoder by calling
the register_adapter method with the type of the
object and a function to convert them to JSON serializable.
Use it with JSON like this:
>>> json.dumps(object ,cls=ModularEncoder)
"""
defaults = {}
@classmethod
def register_adapter(self, type, func):
"""\
Custom types can be added using this function.
calling this method with a type/class and a function to decode
it will make the Encoder call the function with the object
that has the same type. The function should return a JSON serializable
object.
Eg:
>>> from decimal import Decimal
>>> ModularEncoder.register_adapter(Decimal, lambda dec: float(dec))
"""
self.defaults[type] = func
def default(self, o):
func = self.defaults.get(type(o))
if func:
return func(o)
return super().default(o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment