[英]ValueError: invalid literal for int() with base 10: '' I got this error when empty value was sent
I got ValueError: invalid literal for int() with base 10: ''
error. 我得到了ValueError:
invalid literal for int() with base 10: ''
错误。 I wrote 我写
def convert_json(request):
json_body = json.loads(request.body)
return json_body.get('ans', 0)
When I send json like 当我像发送JSON
{ "ans": "" }
the error happens.I really cannot understand why this error happens because I think 0 is returned.In this json,"" means None , so 0 should be returned,I think.But my code did not work wells how should i fix this?What should I write it to make ideal system? 错误发生。我真的不明白为什么会发生此错误,因为我认为返回了0。在此json中,“”表示None,所以我认为应该返回0。但是我的代码无法正常工作,我该如何解决呢?我应该怎么写才能使系统更理想?
In Python, get()
will return the value if it exists in the dictionary, even if the value is an empty string. 在Python中,即使字典中存在值,
get()
也会返回该值,即使该值是一个空字符串也是如此。
You can test this by running the following code in your shell: 您可以通过在外壳程序中运行以下代码来进行测试:
>>> json_body = {"ans": ""}
>>> json_body.get('ans', 0)
''
If you want to convert empty strings to 0
, then you should do this in your convert_json
method. 如果要将空字符串转换为
0
,则应在convert_json
方法中执行此操作。
def convert_json(request):
json_body = json.loads(request.body)
ans = json_body.get('ans', 0)
if ans == '':
ans = 0
return ans
you can chage code to: 您可以修改代码以:
def convert_json(request):
json_body = json.loads(request.body)
return json_body.get('ans') and int(json_body.get('ans')) or 0
In upper code if ans
type wasn't number ValeError raising. 在较高的代码中,如果
ans
类型不是数字,则ValeError提高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.