Typeerror: Object Of Type Decimal Is Not Json Serializable
TypeError: Object of type Decimal is not JSON serializable While I am running in postman api i get the above error because sales_qty is decimal , I dont know how to parse decimal
Solution 1:
Use json.dump with cls argument, I believe that when ever the json module dont know how to convert, it will call the default function.
import json
import decimal
classEncoder(json.JSONEncoder):
defdefault(self, obj):
ifisinstance(obj, decimal.Decimal): returnfloat(obj)
json.dumps( ... , cls = Encoder)
```python
Solution 2:
import decimal
from flask import current_app as app
from flask import Jsonify
from flask.json import JSONEncoder
classJsonEncoder(JSONEncoder):
defdefault(self, obj):
ifisinstance(obj, decimal.Decimal):
returnfloat(obj)
return JSONEncoder.default(self, obj)
@app.route('/test_jsonify')deftest_jsonify():
data = {
'float': 7.5,
'decimal': decimal.Decimal(7.5)
}
app.json_encoder = JsonEncoder
return jsonify(data)
(found here Flask Jsonify Custom JsonEncoder | Lua Software Code)
Post a Comment for "Typeerror: Object Of Type Decimal Is Not Json Serializable"