首页 > 解决方案 > 使用字典将嵌套字典添加到已存在的 JSON 文件中

问题描述

我最近开始学习一些python。在完成所有 learnpython.org 教程后,我正在自己尝试一些东西(所以你知道我的知识水平)。

我想构建一个小脚本,让您构建一个 DnD 角色并将其保存在文件中。这个想法是使用 JSON(因为它包含在 learnpython 教程中)并按照以下方式放入字典:

data = { playerName ; {"Character Name" : characterName, "Character Class" : characterClass...ect.}}

我希望可以将新的 dics 添加到原始数据 dic 内的 JSON 文件中,因此字典是 playerName 的列表,其中包含字符 dics。

我不仅没有完全像这样得到它,而且在不使文件不可读的情况下添加以下字典也失败了。这是我的代码,因为它不是很长:

import json


def dataCollection():
    print("Please write your character name:")
    characterName = input()
    print("%s, a good name! \nNow tell me your race:" % characterName)
    characterRace = input()
    print("And what about the class?")
    characterClass = input()
    print("Ok so we have; \nName = %s \nRace = %s \nClass = %s \nPlease tell me the player name now:" % (characterName, characterRace, characterClass))
    playerName = input()
    print("Nice to meet you %s. \nI will now save your choices..." % playerName)
    localData = { playerName : 
                 {"Character Name" : characterName,
                  "Character Class" : characterClass,
                  "Character Race" : characterRace}}

    with open("%s_data_file.json" % playerName, "a") as write_file:
        json.dump(localData, write_file)
        
    


dataCollection()

with open("data_file.json", "r") as read_file:
    data = json.load(read_file)
# different .json name here since I'm trying around with different files

print(data)

编辑:JSON 也可能不是用于我的想法的“正确”事物。如果您对存储该信息有任何替代想法(除了直接的 txt 文件),请随时提出建议!

标签: pythonjsondictionary

解决方案


我做了一点修改,我尝试读取文件以初始化数据 json,如果它失败我初始化数据。

import json


def createPlayer():
    print("Please write your character name : ")
    characterName = input()
    print("%s, a good name! \nNow tell me your race : " % characterName)
    characterRace = input()
    print("Nice to meet you %s. \nI will now save your choices..." % characterName)

    try :
        with open('data_file.json') as json_file:
            data = json.load(json_file)
    except :
        data = {}
        data['player'] = []

    data['player'].append({
    'name': characterName,
    'race': characterRace,
    })

    with open("data_file.json", "w+") as write_file:
        json.dump(data, write_file)

createPlayer()

with open("data_file.json", "r") as read_file:
    data = json.load(read_file)

print(data)

推荐阅读