有没有办法将正确格式的json信息写入.json文件并在本地读取?

时间:2019-05-10 19:15:49

标签: python json database

我打算将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

1 个答案:

答案 0 :(得分:0)

您要写入json文件的基本项目是一个列表,但是您将其像字典一样对待。它包含词典,但是您必须像列表一样访问它:

print(result[0]['profile']['email'])
print(result[1]['profile']['email'])
# etc.