0

In a Python script, a cursor.fetchall command is returning a list of tuples, some elements of which are marked as e.g. Decimal('0.50') instead of just 0.50.

myList= [(1, 'string1', None, None, 'string2', 0, 'string3'),
(1,   'string1',   Decimal('0.50'),   Decimal('2.5'),   'string2',   3,   'string3')]

The reason I'd like the latter form (i.e. just 0.50) is that I'm trying to send the list using print(json.dumps(result)), which currently returns TypeError: Decimal('0.50') is not JSON serializable.

Is there a direct way to strip away this "type" information? I've been turning around on this without success, and I find previous related questions only cover cases where all elements are of the same type (e.g. here). Thanks for any tips!

Community
  • 1
  • 1
sc28
  • 1,163
  • 4
  • 26
  • 48
  • 1
    This isn't "type information", a `Decimal` object is different from an `int` or ` float`, it is its own class. `decimal.Decimal`. You can probably just do `float(Decimal('0.05')` – juanpa.arrivillaga Apr 26 '17 at 22:37
  • Have you tried http://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object ? – kennytm Apr 26 '17 at 23:09

1 Answers1

0

Here is the way I overcame this issue.

First, I convert the query result into a pandas dataframe:

df = pd.DataFrame(query_data)

Then, I simply convert the troublesome columns to string:

df[2] = [str(r) for r in df[2]]

Finally, I convert the dataframe to a csv string:

df_csv = df.to_csv(sep=',', index = False, header = False) 

And this can be used with no error in print(json.dumps(result)).

Pretty specific workaround, but thought I'd post it anyway to provide at least one answer to the problem.

sc28
  • 1,163
  • 4
  • 26
  • 48