B
B
beduin012018-03-20 16:01:24
Python
beduin01, 2018-03-20 16:01:24

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)

Here is the error itself:
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

I can't understand why when I access an element of a dictionary, I just see its value - `5000.00`, but if I try to serealize everything in JSON, everything breaks off right away. `Decimal('5000.00')' comes out from somewhere`
The asdict() method is taken from here https://pythonhosted.org/dictalchemy/#

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-03-20
@beduin01

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 printtries 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)

A
Alexander, 2018-03-20
@NeiroNx

Because there is an object of type Decimal

>>> from decimal import *
>>> Decimal('5000.00')
Decimal('5000.00')
>>> a = Decimal('5000.00')
>>> a.to_eng_string()
'5000.00'
>>>

must be converted to string type
x['amount'] = x['amount'].to_eng_string()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question