Skip to content

Instantly share code, notes, and snippets.

@daninfpj
Created December 10, 2019 14:12
Show Gist options
  • Save daninfpj/861b7306bbe160f5cb665189a4aae997 to your computer and use it in GitHub Desktop.
Save daninfpj/861b7306bbe160f5cb665189a4aae997 to your computer and use it in GitHub Desktop.
Python JSON Decoder
import json
from decimal import Decimal
class A:
def __init__(self, value):
self.bar = Decimal(value)
def to_dict(self):
return {
"bar": self.bar
}
class Encoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, A):
return o.to_dict()
if isinstance(o, Decimal):
return float(o)
return json.JSONEncoder.default(self, o)
a = A(2)
json.dumps(a, cls=Encoder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment