我计划使用JSON文件作为一个简单的数据库,我试图添加到它的新条目,并尝试采取我的条目以后。
这是我的代码:
import json
import time
try:
with open('json_database.json', 'r') as json_database:
profiles = json.load(json_database)
except FileNotFoundError:
profiles = []
while True:
answer = input('list info (l), write info (w), new info (a)').lower()
if answer == 'w':
break
elif answer == 'l':
print(profiles)
else:
username = input('username: ')
email = input('Email: ')
rating = input('Rating: ')
lichess_profiles.append({
'profile':{
'username': lichess_username,
'email': email,
'rating': rating
}
})
with open('json_database.json', 'w') as json_database:
json.dump(profiles, json_database)现在我想调用JSON信息中的信息!这就是我要说的:
with open('json_database.json') as json_1:
result = json.load(json_1)
print(result['profile']['email'])原因是什么?我该补充些什么呢?
我尝试过这段代码,但它会引发以下错误:
TypeError: list indices must be integers or slices, not str发布于 2019-05-10 19:35:48
您要写入json文件的基本项是一个列表,但您将它视为一个字典。它包含字典,但您必须像列表一样访问它:
print(result[0]['profile']['email'])
print(result[1]['profile']['email'])
# etc.https://stackoverflow.com/questions/56083628
复制相似问题