JSON only allows strings as keys.
The code below uses a custom JSONEncoder to turn Decimal values into strings.
Is there a way to specify an encoder that will turn Decimal keys into strings?
import json
import decimal
class DecimalEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return str(obj)
return json.JSONEncoder.default(self, obj)
d1 = {3: decimal.Decimal(50)}
print(json.dumps(d1, cls=DecimalEncoder))
d2 = {decimal.Decimal(50): 3}
json.dumps(d2, cls=DecimalEncoder) # TypeError: keys must be a string
I am using python3.6.
Note: Obviously I could iterate through my dictionary and replace the Decimal types with string values, but I am hoping to find a more elegant solution perhaps by adding behaviour to the encoder.