首页 > 解决方案 > 将数据附加到 .json-File + cleanup json-Method 中的特定值

问题描述

我刚开始用 Python 构建自己的 Twitch Bot。现在我想建立一个投票功能。我将数据推送到 .json 文件中,因为我需要从 Web 界面访问数据以控制投票(设置问题、激活/取消激活、在 CasparCG 服务器上播放)并将其推送到我的 GC-服务器(CasparCG)在我的 Stream 上显示它。

@bot.command(name="vote")
async def vote(ctx):
    with open("poll.json", "r+") as f:
     data = json.loads(f.read())
     vote_active = (data['poll_active'])
     vote_options = (data['vote_options']['options'])
     print("json File has been read") #Debug
     print("Vote Options:") #Debug
     print(vote_options) #Debug
     print("Vote Active:") #Debug
     print(vote_active) #Debug
     pollOptions = vote_options
     if ctx.author.name not in pollEntrants and vote_active:
        try:
            vote = int(ctx.message.content.split("vote ")[1])
            pollOptions[list(pollOptions.keys())[vote-1]] += 1
            pollEntrants.append(ctx.author.name)
            print ("I did count that!") #Debug
            print(pollEntrants) #Debug
            print(pollOptions) #Debug
        except IndexError:
            pass
     else:
        print ("I didnt't count that!") #Debug
        print(pollEntrants) #Debug
        print(pollOptions) #Debug
        pass

这是我的 poll.json:

{
    "question": "Testquestion",
    "question_desc": "Questiondescription",
    "question_desc_size": "155%",
    "poll_active": true,
    "options": {
        "option1": "Answer 1",
        "option2": "Answer 2",
        "option3": "Answer 3",
        "option4": "Answer 4"
    },
    "vote_options": {
        "options": {
            "opt_1": 0,
            "opt_2": 0,
            "opt_3": 0,
            "opt_4": 0
        }
    }
}

所以首先要做的事情...... json-File 处理是在投票功能中实现的。为了保持函数更干净,我尝试使用 get_voteopts(): Function。

def get_voteopts():
 global vote_options
 global vote_active
with open("poll.json") as f:
     data = json.loads(f.read())
     vote_active = (data['poll_active'])
     vote_options = (data['vote_options']['options'])
     print(vote_options)

但是用“get_voteopts()”调用那个函数什么也没做。当我重新启动脚本时,该函数被调用一次,并且只会再次被调用。这很糟糕,因为 json-File 只检查一次,我无法检查文件是否已在外部更改。但是将它直接放在投票函数中可以满足我的要求。

主要问题和我寻求帮助的原因:

我想将收集到的数据写回它来自的 json-File 中的位置。所以我希望我的脚本更新 json-File 的一部分 vote_options、options、opt_1、2、3 中的值。

有人可以帮我解决这个问题吗?也许一开始就选择 json 不好。:D 如果我的计划太复杂,也许有人可以建议我另一种文件格式?XML?亚美尔?

问候

标签: pythonjsontwitchvoting-system

解决方案


好的。我想我自己修好了。但也许有人知道是否有更清洁的方法来做到这一点?

这就是它现在的样子。

我打开字典 ( data),然后选择确切的键,然后使用该.update功能更新它们。

@bot.command(name="vote")
async def vote(ctx):
    with open("poll.json", "r+") as f:
     data = json.loads(f.read())
     vote_active = (data['poll_active'])
     vote_options = (data['vote_options']['options'])
     print("json Datei read") #Debug
     print("Vote Options:") #Debug
     print(vote_options) #Debug
     print("Vote Active:") #Debug
     print(vote_active) #Debug
     print ("Content of dict")
     print(data)
     
     if ctx.author.name not in pollEntrants and vote_active:
        try:
            vote = int(ctx.message.content.split("vote ")[1])
            if vote is not None or (vote == 0):
               vote_options[list(vote_options.keys())[vote-1]] += 1
               pollEntrants.append(ctx.author.name)
               data['vote_options']['options'].update(vote_options)
               f.seek(0)
               f.write(json.dumps(data, indent=4))
               f.close
               print ("I did count that!") #Debug
               print(pollEntrants) #Debug
               print(vote_options) #Debug
            else:
                pass
        except IndexError:
             pass
     else:
        print ("I didnt't count that!") #Debug
        print(pollEntrants) #Debug
        print(vote_options) #Debug
        pass

推荐阅读