Python下json报错?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python下json报错?相关的知识,希望对你有一定的参考价值。
import json
def get_stored_username():
"""Get stored username if available."""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""Prompt for a new username."""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dumpsS(username, f_obj)
return username
def greet_user():
"""Greet the user by name."""
username = get_stored_username()
if username:
correct = input("Are you " + username + "? (y/n) ")
if correct == 'y':
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
greet_user()
以上代码是书上的练习题答案,但为什么Python运行这个会报错?以下是运行结果:
Traceback (most recent call last):
File "E:/python/wenjian/10.4.1.2.py", line 36, in <module>
greet_user()
File "E:/python/wenjian/10.4.1.2.py", line 24, in greet_user
username = get_stored_username()
File "E:/python/wenjian/10.4.1.2.py", line 8, in get_stored_username
username = json.load(f_obj)
File "E:\python\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "E:\python\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "E:\python\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "E:\python\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
第一行就不满足json结构 参考技术A 报错麻烦吧错误异常贴出来看看,很可能你的json内容不符合规范,建议先检查下。
python 报错之解决办法
PUT 之 400 解决办法
json parse error:Unrecognized token "id":was expecting(‘true’,\'false\' or \'null\')
传参格式不正确,没有识别出json ,dict 转化称json,解决办法如下:添加 json.dumps(data)
以上是关于Python下json报错?的主要内容,如果未能解决你的问题,请参考以下文章
python json.loads 报错 json.decoder.JSONDecodeError
python操作:json文件中存在NumberInt(0),没有引号,无法解析?