Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created August 9, 2019 15:34
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 jsbueno/5f5d200fd77dd1233c3063ad6ecb2eee to your computer and use it in GitHub Desktop.
Save jsbueno/5f5d200fd77dd1233c3063ad6ecb2eee to your computer and use it in GitHub Desktop.
Python JSON Encoder able to encode arbitrary precision decimals as numbers
import json, re, uuid
class JsonDecimalAwareEncoder(json.JSONEncoder):
def __init__(self, *args, **kw):
self.original_numbers = {}
super().__init__(*args, **kw)
def default(self, obj):
if isinstance(obj, decimal.Decimal):
key = uuid.uuid4()
self.original_numbers[key] = obj
return f"__CUSTOM_ENC_{key}__"
return super().default(obj)
def replace(self, match):
key = uuid.UUID(match.groups()[0])
return str(self.original_numbers[key])
def encode(self, obj):
intermediary = super().encode(obj)
expr = re.compile(f"\\\"__CUSTOM_ENC_({'|'.join(str(key) for key in self.original_numbers)})__\\\"")
result = expr.sub(self.replace, intermediary)
return result
@jsbueno
Copy link
Author

jsbueno commented Aug 9, 2019

Python can already decode arbitrary decimal numbers, all that is needed is to pass a parse_float argument to standard json.loads call like in: json.loads(data, parse_float=decimal.Decimal) . To encode using this recibe, just do: data= JsonDecimalAwareEncoder().encode(obj)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment