[英]Python - Json write, Doesn't want to print out as I wish
我试图从我的脚本中进行写操作以使其成为Json文件。
但是,当我用脚本写出来时,它的输出为
{
"profile_1": {
"email": "HelloWorld",
"pswrd": "WorldHello123"
}
} {
"profile_2": {
"email": "HelloWorld",
"pswrd": "WorldHello123"
}
} {
"profile_3": {
"email": "HelloWorld",
"pswrd": "WorldHello123"
}
}
我真正希望的是:
"profile_0": {
"email": "HelloWorld",
"pswrd": "WorldHello123"
},
"profile_1": {
"email": "HelloWorld",
"pswrd": "WorldHello123""
},
"profile_2": {
"email": "HelloWorld",
"pswrd": "WorldHello123"
},
"profile_3": {
"email": "HelloWorld",
"pswrd": "WorldHello123"
},
而且,根据我们的比较,{}太多了,而且也缺少了,我不太明白为什么它行不通。 这是我的脚本的工作方式:
import json
with open("test.txt") as accounts:
for splitlines in accounts:
temp = accounts.read().splitlines()
username, password = zip(*(s.split(":") for s in temp))
linelength = len(username)
with open("profiles.json", "a") as profile:
lineInt = 0
while (lineInt < linelength):
lineInt += 1
jsonData = {
"profile_" + str(lineInt): {
"email": username[lineInt],
"pswrd": password[lineInt]
}
}
json.dump(jsonData, profile)
我坐了太久没看到问题了:'(
您正在逐一输出JSON对象 。 如果要输出JSON数组 ,则应将对象放在列表中,并进行打印,例如:
lineInt = 0
items = []
while (lineInt < linelength):
jsonData = {
"profile_" + str(lineInt): {
"email": username[lineInt],
"pswrd": password[lineInt]
}
}
lineInt += 1
items.append(jsonData)
json.dump(items, profile)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.