Created
August 9, 2019 15:34
-
-
Save jsbueno/5f5d200fd77dd1233c3063ad6ecb2eee to your computer and use it in GitHub Desktop.
Python JSON Encoder able to encode arbitrary precision decimals as numbers
This file contains 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, 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python can already decode arbitrary decimal numbers, all that is needed is to pass a
parse_float
argument to standardjson.loads
call like in:json.loads(data, parse_float=decimal.Decimal)
. To encode using this recibe, just do:data= JsonDecimalAwareEncoder().encode(obj)