[英]Is there a way to write a correct-form json info to a .json file and read from it locally?
我打算將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
您要寫入json文件的基本項目是一個列表,但是您將其像字典一樣對待。 它包含字典,但是您必須像列表一樣訪問它:
print(result[0]['profile']['email'])
print(result[1]['profile']['email'])
# etc.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.