Created
December 10, 2019 14:12
-
-
Save daninfpj/861b7306bbe160f5cb665189a4aae997 to your computer and use it in GitHub Desktop.
Python JSON Decoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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