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:
- 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)
- 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
Django Login - Missing 1 Required Positional Argument
How to Change Border Color in Tkinter Widget
How to Skip Blank Line While Reading CSV File Using Python
Converting Json into Newline Delimited Json in Python
Python Pandas: Nameerror: Name Is Not Defined
Paramiko Capturing Command Output
Tkinter Ttk Treeview How to Set Fixed Width Why It Change With Number of Column
How to Avoid Last Comma in Python Loop
Reading Contents of a Gzip File from a Aws S3 in Python
How to Click on an Element from the Dropdown Menu Through Python and Selenium
Python Replace Single Quotes Except Apostrophes
Python-Compare Two String Columns in Same Dataframe, Return Matching Result
What Is the Most Efficient Way to Sum a Dict With Multiple Keys by One Key
Pandas To_Csv: Suppress Scientific Notation in CSV File When Writing Pandas to Csv
How to Get a Fields Particular Value of Json in Python
How to Read a File Without Newlines
Error! C:\File\Example.Db Is Not Utf-8 Encoded Ipython Notebook