I have a Decimal(\'3.9\')
as part of an object, and wish to encode this to a JSON string which should look like {\'x\': 3.9}
. I don\'t care about p
From the JSON Standard Document, as linked in json.org:
JSON is agnostic about the semantics of numbers. In any programming language, there can be a variety of number types of various capacities and complements, fixed or floating, binary or decimal. That can make interchange between different programming languages difficult. JSON instead offers only the representation of numbers that humans use: a sequence of digits. All programming languages know how to make sense of digit sequences even if they disagree on internal representations. That is enough to allow interchange.
So it's actually accurate to represent Decimals as numbers (rather than strings) in JSON. Bellow lies a possible solution to the problem.
Define a custom JSON encoder:
import json
class CustomJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return super(CustomJsonEncoder, self).default(obj)
Then use it when serializing your data:
json.dumps(data, cls=CustomJsonEncoder)
As noted from comments on the other answers, older versions of python might mess up the representation when converting to float, but that's not the case anymore.
To get the decimal back in Python:
Decimal(str(value))
This solution is hinted in Python 3.0 documentation on decimals:
To create a Decimal from a float, first convert it to a string.