JSON解析不正确,即使它应该

2024-05-14 12:46:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在为GCSE计算机科学的NEA工作,我正在尝试将JSON合并到我的项目中,以便以后更容易地访问数据

我试过运行其他JSON,但由于某种原因,我生成的JSON无法解析到python列表中

with open('userProfiles.json', 'r+') as f: #Open up the json file for reading/writing.
    print(f.read()) # Debug message to check if f.read actually contains anything...
    currentProfiles = json.loads(f.read()) # Load the json into a useable list.
    print(currentProfiles) # Debug Message: So I can check if the list loads properly
    username = input("Enter username: ")
    password = hashlib.sha256((input("Enter Password: ")).encode('utf-8')).hexdigest() # Create an sha256 hash to be used later to authenticate users.
    newUser = json.dumps({'users':[{'username':username, 'password':password}]}, sort_keys=True, indent=4)
    f.write(newUser)

这是我注释掉加载代码时它生成的JSON文件

{
    "users": [
        {
            "password": "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918",
            "username": "Admin"
        }
    ]
}

我想把这个JSON加载到一个列表中,这样我就可以在需要时用另一个用户扩展它,但是我不能,因为错误消息:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

每当我尝试解析JSON时,我都会通过一个在线验证器运行JSON,它告诉我它是有效的JSON。我似乎在这里找不到问题


Tags: thetodebugjson列表readifcheck
1条回答
网友
1楼 · 发布于 2024-05-14 12:46:55

调用read()读取整个文件,并将读取光标留在文件的末尾(没有其他内容可读取)

with open('userProfiles.json', 'r') as f: #Open up the json file for reading/writing.
    data = f.read()
    print(data) # Debug message to check if f.read actually contains anything...
    currentProfiles = json.loads(data) # Load the json into a useable list.
    print(currentProfiles) # Debug Message: So I can check if the list loads properly
    username = input("Enter username: ")
    password = hashlib.sha256((input("Enter Password: ")).encode('utf-8')).hexdigest() # Create an sha256 hash to be used later to authenticate users.
    newUser = json.dumps({'users':[{'username':username, 'password':password}]}, sort_keys=True, indent=4)

with open('userProfiles.json', 'a') as f:
    f.write(newUser)

相关问题 更多 >

    热门问题