I asked this question earlier, and it was marked as duplicate of this, but the accepted answer does not work and even pylint shows that there are errors in the code.
What I want to do:
from decimal import Decimal
import json
thang = {
'Items': [{'contact_id': Decimal('2'), 'street_name': 'Asdasd'}, {'contact_id': Decimal('1'), 'name': 'Lukas', 'customer_id': Decimal('1')}],
'Count': 2}
print(json.dumps(thang))
This throws:
TypeError: Object of type 'Decimal' is not JSON serializable
So I tried the linked answer:
from decimal import Decimal
import json
thang = {
'Items': [{'contact_id': Decimal('2'), 'street_name': 'Asdasd'}, {'contact_id': Decimal('1'), 'name': 'Lukas', 'customer_id': Decimal('1')}],
'Count': 2}
class DecimalEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
if isinstance(o, Decimal):
# wanted a simple yield str(o) in the next line,
# but that would mean a yield on the line with super(...),
# which wouldn't work (see my comment below), so...
return (str(o) for o in [o])
return super(DecimalEncoder, self)._iterencode(o, markers)
print(json.dumps(thang, cls=DecimalEncoder))
And here the linter shows that line return super(DecimalEncoder, self)._iterencode(o, markers)
has errors, because Super of 'DecimalEncoder' has no '_iterencode' member
and when ran throws
TypeError: Object of type 'Decimal' is not JSON serializable
How do I make this work?