首页 > 解决方案 > JSON文件未读取

问题描述

import json
import io

username = input('Enter your username ') #Input
password = input('Now enter your password ') #Input

usernamelow = username.lower() 

用户名输入转换为小写

auth = {
    "users": usernamelow,
    "pass": password
    }

写入 JSON 文件的 JSON 字符串

dump = json.dumps(auth) #Gathers data
print (dump) #Debug print
with open('auth.json', 'a') as outfile:
    for line in outfile:
        json.dump(auth, outfile, indent=4)

(Dumps AUTH) 将数据添加到 JSON 文件 ^

with open('auth.json', 'r') as f:
    data = json.load(f)

基本上这是我正在从事的一个学校项目,当我多次附加到文件时,它会给我一个额外的数据错误。这是运行脚本时出现的 JSON:

{
    "pass": "testpass", 
    "users": "testuser"
}{
    "users": "testinguser", 
    "pass": "testingpass"
}

我似乎收到此错误:

ValueError:额外数据:第 4 行第 2 列 - 第 7 行第 2 列(字符 52 - 110)

标签: pythonjson

解决方案


好的,下面的错误告诉我们一些事情:-

ValueError: Extra data

您尝试加载的数据在 JSON 中的格式不正确。正确的 JSON 格式应该是:-

[{
    "pass": "testpass", 
    "users": "testuser"
}, {
    "users": "testinguser", 
    "pass": "testingpass"
}]

更好的做法是在字典列表中输入所有数据一次,然后您可以将其作为一个整体转储到文件中:-

with open('auth.json', 'a') as outfile:
    json.dump(auth_list, outfile, indent=4)

推荐阅读