Last active
August 29, 2015 14:08
-
-
Save sunliwen/e1d305abbd0931fee107 to your computer and use it in GitHub Desktop.
Demonstrate how to loads/dumps json with float value as decimal.Decimal in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import decimal | |
import pprint | |
# refs: https://djangosnippets.org/snippets/2410/ | |
# refs: http://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object | |
class DecimalEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, decimal.Decimal): | |
return float(obj) | |
return json.JSONEncoder.default(self, obj) | |
a = {'decimal': decimal.Decimal('3.14')} | |
try: | |
print("failed to dumps {}".format(repr(a))) | |
pprint.pprint(json.dumps(a)) | |
except Exception as ex: | |
print(ex) | |
# Output has one decimal, change format if you need more | |
json.encoder.FLOAT_REPR = lambda o: format(o, '.1f') | |
print("successfully dumps {}".format(repr(a))) | |
pprint.pprint(json.dumps(a, cls=DecimalEncoder)) | |
b = '{"decimal": 3.14}' | |
print("successfully loads {}".format(repr(b))) | |
pprint.pprint(json.loads(b, parse_float=decimal.Decimal)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment