Reputation: 59
I am trying to make a post request to a third party application along with some data and the data also have a decimal value up to two points, which I am getting from database (order.amount) but after making the request getting error saying data is not serializable to json then i passed it as '"%s"' % round(order.amount,2) then also getting error post data is empty.Looking for suggestion to solve this problem.
request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2)
transferId=transfer_identifier,remarks="Test transfer")
getting error: decimal is not json serializable
print('"%s"' % round((order.amount),2) #"5000.23"
request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"}
but when hardcoding amount then it is working
request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer")
Upvotes: 0
Views: 1140
Reputation: 60
Pay attention to this line,
print('"%s"' % round((order.amount),2) #"5000.23"
I guess you miss one thing: you're formatting your decimal value, but you do this with quotes, so your variable amount
will contain "5000.23"
string instead of 5000.23
.
So, look:
request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
you have amount='"5000.23"'
and these quotes get in the way of serialization.
To fix it, just remove the additional quotes:
print('%s' % round((order.amount),2) # '5000.23'
request = Transfer.request_transfer(beneId=beneficiary_id, amount='%s' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")
Upvotes: 1
Reputation: 21802
The round
function according to Python docs:
The return value is an integer if ndigits is omitted or
None
. Otherwise the return value has the same type as number.
Hence round
when passed a Decimal
and ndigits
will return a Decimal
, hence passing amount=round((order.amount),2)
will not do what you assume it does (converting to float
or int
). Also converting Decimal
to float
implies a loss of precision which we don't want (The whole reason we would be using Decimal
). To pass a Decimal
value one would simply pass it as a string (Which of course implies we would need to perform some type casting at the client side if we want to perform arithmetic using it):
request = Transfer.request_transfer(
beneId=beneficiary_id,
amount=str(order.amount),
transferId=transfer_identifier,
remarks="Test transfer"
)
Upvotes: 0