Python Json Serialize a Decimal Object

Python JSON serialize a Decimal object

How about subclassing json.JSONEncoder?

class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.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).default(o)

Then use it like so:

json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)

Object of type 'Decimal' is not JSON serializable

It seems you have two options:

  1. Probably easiest, you can serialize the int/float value of a Decimal object:

""" assume d is your decimal object """

serializable_d = int(d) # or float(d)

d_json = json.dumps(d)


  1. You can add simplejson to your requirements.txt, which now has support for serializing Decimals. It's a drop-in replacement for the included json module.
import simplejson as json # instead of import json

The rest of your code will work the same. If you need further assistance, kindly leave a comment.

Python 3.5 JSON serialize a Decimal object

Answering my own question.
I output Decimal objects surrounded by special character `. Then remove it and the double-quote from text.

class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return '`'+str(o)+'`' #` is special, will be removed later
return super(DecimalEncoder, self).default(o)

json.dumps(y, cls=DecimalEncoder).replace("\"`",'').replace("`\"",'')

Python 3.x cannot serialize Decimal() to JSON

That answer turned out to be outdated and there was another answer with the working solution:

class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return str(o)
return super(DecimalEncoder, self).default(o)

Note that this will convert the decimal to its string representation (e.g.; "1.2300") to a. not lose significant digits and b. prevent rounding errors.

Python json TypeError: Object of type Decimal is not JSON serializable

A custom encoder for specific json values (including Decimal) can be used as suggested here. In this example, Decimal should presumably be converted to float:

import json
from decimal import Decimal

#Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)

#...
result = json.dumps(table_scan, cls=JSONEncoder) #Works!

Python to JSON Serialization fails on Decimal

It is not (no longer) recommended you create a subclass; the json.dump() and json.dumps() functions take a default function:

def decimal_default(obj):
if isinstance(obj, decimal.Decimal):
return float(obj)
raise TypeError

json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)

Demo:

>>> def decimal_default(obj):
... if isinstance(obj, decimal.Decimal):
... return float(obj)
... raise TypeError
...
>>> json.dumps({'x': decimal.Decimal('5.5')}, default=decimal_default)
'{"x": 5.5}'

The code you found only worked on Python 2.6 and overrides a private method that is no longer called in later versions.



Related Topics



Leave a reply



Submit