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

时间:2019-05-27 12:35:48

标签: python json

我目前正在为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。我似乎在这里找不到问题。

1 个答案:

答案 0 :(得分:0)

调用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)