MacHu-GWU / superjson-project

Extendable json encode/decode library.
MIT License
2 stars 0 forks source link

Object of type Decimal is not JSON serializable #2

Open passitalong opened 2 years ago

passitalong commented 2 years ago

Would you be open to adding support for type DECIMAL?

MacHu-GWU commented 2 years ago

@passitalong good idea, you can watch this thread I will at you when the feature is added

MacHu-GWU commented 2 years ago

@passitalong I just did some research. The best method to serialize a Decimal object in the community is not even close. The purpose of Decimal is to preserve the unlimit precision, For example, result = Decimal(1) / Decimal(7). The result object will not store the result directly. It actually stores the expression and only evaluate the value when you print or use it.

The only way to serialize it without losing precision is to serialize the entire match expression. I don't think it is worth to convert a decimal back to expression.

In conclusion, you should not serialize it in anyway, don't json, don't pickle, because the purpose of Decimal is to preserve precision. If you don't care precision, I think you should convert to float and then convert back to decimal.

I am still thinking that if this library has to support this feature, the only way is to convert it to float first, but we lose precision. I am not sure if it is the best way to do that.

passitalong commented 2 years ago

This totally makes sense. Thank you for looking into this. Much appreciated.