I have a class in Python called TransactionData
:
from dataclasses import dataclass
from decimal import *
@dataclass(unsafe_hash=True)
class TransactionData:
date: str
transaction: str
cheque_no: str
debit: Decimal
credit: Decimal
balance: Decimal
def __post_init__(self):
if not isinstance(self.date, str):
raise ValueError('date provided is not a string.')
if not isinstance(self.transaction, str):
raise ValueError('transaction provided is not a string.')
if not isinstance(self.cheque_no, str):
raise ValueError('cheque_no provided is not a string.')
if not isinstance(self.debit, Decimal):
raise ValueError('debit provided is not a Decimal.')
if not isinstance(self.credit, Decimal):
raise ValueError('credit provided is not a Decimal.')
if not isinstance(self.balance, Decimal):
raise ValueError('balance provided is not a Decimal.')
I want to serialize it to a Json with json.dumps()
. I have extended JSONEncoder
to be able to serialize Decimal
:
import decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return str(o)
return super(DecimalEncoder, self).default(o)
Now I try to serialize TransactionData
:
transaction = TransactionData(
'28 Aug','Cheque', '187264', Decimal('100.00'), Decimal('200.00'), Decimal('300.00'))
json.dumps(transaction, cls=DecimalEncoder)
I'm getting this error:
TypeError: Object of type TransactionData is not JSON serializable
I've heard you can use simplejson
for this but I would still prefer to use the standard json library going forward. What is the solution to this?