python - 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)
解决方案
好的,下面的错误告诉我们一些事情:-
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)
推荐阅读
- node.js - 如何在 pg-promise 事务中包装 graphql 请求
- angular - “void”类型上不存在属性“profile”
- node.js - 文件上传适用于邮递员,但不适用于 angular2
- javascript - WordPress AJAX 表单/jQuery 未在后端更新用户元数据
- boost - gdb 从不同位置查找标头
- mysql - creating primary key on two columns which are unique together
- header - 错误要求:Volley 400
- html - Bootstrap 4 columns not working
- dhis-2 - DHIS2 and mysql?
- amazon-web-services - Amazon Cloudfront 和 EC2 重定向设置