Answer the question
In order to leave comments, you need to log in
Why does an extra parameter end up in a Python dictionary?
I need to pull the data from the database and turn it into a json array. Here is my code:
for tr in session.query(MyData).all():
x = tr.asdict()
print('as dict: ', x)
print('print amount: ')
print(x['amount'])
print('---------')
tr_list.append(tr.asdict())
answer = json.dumps(tr_list)
print amount:
5000.00
---------
as dict: {'amount': Decimal('5000.00'), 'id': 6225148}
print amount:
5000.00
---------
Can't decode DB answer to JSON. Exception: Decimal('5000.00') is not JSON serializable
Answer the question
In order to leave comments, you need to log in
This is not an extra option. To store amounts of money for which rounding and overflow errors are not allowed, the special type Decimal is used .
Everything that you output, the function print
tries to convert to a string, and the json module does not know whether it is correct to convert an unknown type to a string and throws an exception.
You can define your own encoder that understands Decimal:
import json
from decimal import Decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return str(obj)
return super(DecimalEncoder, self).default(obj)
json.dumps(tr_list, cls=DecimalEncoder)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question