json.decoder.JSONDecodeError:期望值:第1行第1列(char 0)如何解决?

问题描述 投票:0回答:1
import json
filename = 'username.json'
try:
    with open(filename) as fo:
        username = json.loads(fo)
except FileNotFoundError:
    user = input("Tell me your username?  ")
    print("I'll remember you next time! " + user + " !")
    with open(filename ,'w') as fo:
        json.dump(user ,fo)
else:
    print("So we meet again " +userame +" !")

输出:

PS C:\Users\gagan\Desktop\python crash course> python jsonfile.pyTraceback (most recent call last):
  File "jsonfile.py", line 5, in <module>
    username = json.loads(str(fo))
  File "C:\Users\gagan\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\gagan\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\gagan\AppData\Local\Programs\Python\Python37-32\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)
python json
1个回答
2
投票

您正在将文件句柄传递给json.loads,它需要一个字符串。相反,你要么使用json.load(没有's'):

username = json.load(fo)

或者使用文件内容使用json.loads(末尾的's',代表'string'):

username = json.loads(fo.read())
© www.soinside.com 2019 - 2024. All rights reserved.