比较python中的2个JSON文件,检查项目是否已更改

2024-05-04 05:06:15 发布

您现在位置:Python中文网/ 问答频道 /正文

也许这个标题有点让人困惑,但我的大脑已经被这个问题困扰了好几天了。这就是我的“问题”。我正在重做我的Discord机器人,我有一个小任务,将检查2个JSON文件(相同的格式,不同的数据),它们之间有差异,它将发送一条消息

此代码需要加载2个JSON文件(“VATSIM_DATA_old.JSON和VATSIM_DATA_new.JSON”),并对它们进行比较,找出差异。现在为了简单起见,我减少了代码,这样我就可以知道是否有人在线,以及他们是否不再在线

我的流程是这样的: -当机器人启动时,获取JSON数据并将其保存到文件中,以便我们可以将更新的数据与此文件进行比较, -现在是时候通过从同一链接获取新数据并将其保存到新文件来检查是否有人联机了, -将这两个文件作为JSON加载,这样我们就可以找到其中的所有项目,并比较其中是否有一些项目同时存在或仅存在于其中一个文件中, -在比较它们并执行诸如向通道发送消息之类的操作之后,让我们将新数据保存到旧的_data.json文件中,然后进入睡眠状态X分钟(我将其设置为5)

我遇到的问题是,每次启动任务时,它都会发送相同的消息。所以我这里的逻辑是好的,让我们检查一下文件是否在更改,它们是否在更改,但是代码仍然不知何故忽略了部分代码,该代码告诉他如果数据没有更改,那么只需传递

这是我的代码:

atc = ["ADR_CTR", "ADR_W_CTR", "ADR_U_CTR", "ADR_E_CTR"] #this is short version of array which needs to be checked. This will most likely be moved to the config file so code is cleaner
@tasks.loop(minutes=5)
    async def atcAnnoucements(self):
        #Load old and new VATSIM Data for comparing!
        with open("VATSIM_Data_old.json", encoding="utf-8") as f:
            data = json.load(f)
        file = open("VATSIM_Data_new.json", "w", encoding="utf-8")
        file.write(requests.get('https://data.vatsim.net/vatsim-data.json').text)
        file.close()
        with open("VATSIM_Data_new.json", encoding="utf-8") as s:
            data1 = json.load(s)

        #Check if new VATSIM data contains some changes in online atc
        #If callsign from atc array is present in VATSIM_Data_old it will check is same controller active or not
        #If the controller is not changed it will skip, if new controller comes online it will send a message that the ATC station came online
        for item in data1['clients']:
            if item['callsign'] in data['clients']:
                pass
                    
            else:
                if item['callsign'] in atc:
                    time_start = item['time_logon']
                    time_logg = time_start[:19]
                    logon_start = datetime.strptime(time_logg, '%Y-%m-%dT%H:%M:%S')
                    time_logon = logon_start.strftime('%H:%M')
                    channel = self.bot.get_channel(781834455765483562)
                    embed = Embed(title="ATC Annoucement", description="`New controller just logged in!`", color=0x00ff4c)

                    embed.add_field(name='Position', value=f"`{item['callsign']}`", inline=False)
                    embed.add_field(name='Frequency', value=f"`{item['frequency']}`", inline=False)
                    embed.add_field(name='Controller', value=f"`{item['realname']}`", inline=False)
                    embed.set_footer(text=f"Logged on at: {time_logon}")
                    await channel.send(embed=embed)


            if item['callsign'] in data['clients'] and atc and not data1['clients']:
                channel = self.bot.get_channel(781834455765483562)
                embed2 = Embed(title="ATC Logged off!", description=f"{item['callsign']} just logged off!", color=0xff8800)
                await channel.send(embed=embed2)

        file = open("VATSIM_Data_old.json", "w", encoding="utf-8")
        file.write(requests.get('https://data.vatsim.net/vatsim-data.json').text)
        file.close()
        print("Saved new VATSIM Data!")

编辑: 在我第一次尝试只获取一条消息时,我做了一些类似于下面代码的事情,并且成功了。但一旦我改变了上面的代码,它就会再次发送相同的消息

json1 = open("VATSIM_Data_old.json", "r", encoding="utf-8").read()
        xy = json.dumps(json1)
        s1 = json.loads(xy)
        t = requests.get('https://data.vatsim.net/vatsim-data.json').json()
        xx = json.dumps(t)
        s = json.loads(xx)

                for item in s['clients']:
            if item['callsign'] in atc:
                if item['callsign'] in s1: 
                    pass
                    
                else:
                    if item['callsign'] in atc:
                        time_start = item['time_logon']
                        time_logg = time_start[:19]
                        logon_start = datetime.strptime(time_logg, '%Y-%m-%dT%H:%M:%S')
                        time_logon = logon_start.strftime('%H:%M')
                        channel = self.bot.get_channel(781834455765483562)
                        embed = Embed(title="ATC Annoucement", description="`New controller just logged in!`", color=0x00ff4c)

                        embed.add_field(name='Position', value=f"`{item['callsign']}`", inline=False)
                        embed.add_field(name='Frequency', value=f"`{item['frequency']}`", inline=False)
                        embed.add_field(name='Controller', value=f"`{item['realname']}`", inline=False)
                        embed.set_footer(text=f"Logged on at: {time_logon}")
                        await channel.send(embed=embed)```

Tags: 文件代码injsondataiftimechannel