Skip to content

Instantly share code, notes, and snippets.

@sunliwen
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunliwen/e1d305abbd0931fee107 to your computer and use it in GitHub Desktop.
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
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