检查来自两个不同JSON文件的JSON对象中的值是否相似,并使用python创建匹配结果的列表

2024-09-30 10:40:01 发布

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

我试图最小化从API发送到应用程序的数据,但是有些值是空的,但是可以在另一个API中找到,所以我考虑在服务器上运行一个python脚本,将这些空结果添加到原始JSON文件中。在

我将存储有该信息的列表附加到与原始JSON文件中匹配的列表中,这可以通过使用与两个文件中的视频游戏标题对应的唯一ID来完成。我的代码是:

import json


games = open('outputgames.json')
releases = open('outputreleases.json')

games_json = json.load(games)
releases_json = json.load(releases)

# This is where all the results are found in the JSON file
# The results are all stored in a list, so to access the first result 
# we would access it like this: games_json['results'][0] or games_data[0]

games_data = games_json['results']
releases_data = releases_json['results]

#This is where, i iterate through the data to see IF the id in the object 'game' which is found in releases_data 
#is similar to the one in games_data and then storing both matching results in a Dictionary and a list 
#then i just dump the results to a json file.

grouped_data = [dict(data_releases = x, data_games= i ) for x in releases_data for i in games_data if i['id'] == x['game']['id']]

with open('final_results.json', mode = 'w') as f:
    json.dump(grouped_data, f)

游戏数据['results']中的初始列表包含大约480个结果,而在releases\u data['results']中的初始列表包含470个结果。但由于某些原因,我的代码似乎跳过了一些结果,我应该收到大约480个结果,但我只得到了大约260个结果。我猜我用“IF”语句进行的迭代会跳过它已经传递的一些id,但我不确定。如果有人能帮我使If语句不是从它离开的地方继续,而是从顶部恢复,并实际检查所有id是否匹配。在

如果有人能帮我解决这个问题,或者我做错了什么。任何帮助都很好,谢谢。在

下面是分组的数据将返回什么样的示例,这只是一个条目。当使用json文件运行时,它返回大约260个,但是正如我之前所说,我应该得到更多返回的数百个:

^{pr2}$

下面是一个“releases\u data”和“games\u data”的示例,它们在结果中没有返回,但实际上与ID匹配:

发布数据:

^{3}$

游戏数据:

{"deck":"Orion Trail is a single player choose-your-own-space-adventure.","id":50627,"image":{"icon_url":"http:\/\/static.giantbomb.com\/uploads\/square_avatar\/29\/291401\/2775039-6490638002-heade.jpg","medium_url":"http:\/\/static.giantbomb.com\/uploads\/scale_medium\/29\/291401\/2775039-6490638002-heade.jpg","screen_url":"http:\/\/static.giantbomb.com\/uploads\/screen_medium\/29\/291401\/2775039-6490638002-heade.jpg","small_url":"http:\/\/static.giantbomb.com\/uploads\/scale_small\/29\/291401\/2775039-6490638002-heade.jpg","super_url":"http:\/\/static.giantbomb.com\/uploads\/scale_large\/29\/291401\/2775039-6490638002-heade.jpg","thumb_url":"http:\/\/static.giantbomb.com\/uploads\/scale_avatar\/29\/291401\/2775039-6490638002-heade.jpg","tiny_url":"http:\/\/static.giantbomb.com\/uploads\/square_mini\/29\/291401\/2775039-6490638002-heade.jpg"}}

Tags: theincomjsonhttpurldatastatic
1条回答
网友
1楼 · 发布于 2024-09-30 10:40:01

编辑:这是不正确的。我把它作为评论的背景。在

您为releases\u数据发布的示例的问题在于第一个字段:"deck":null如果我试图从这个字符串创建一个JSON对象,我得到

builtins.NameError: name 'null' is not defined

一定有某个try-catch块忽略此异常。你可以定义一下

^{pr2}$

在处理文件之前,如果这是唯一的问题。也许您应该测试一下从这两个文件中每个文件可以创建多少个JSON对象,以找到任何其他问题,然后再返回合并它们。在

作为一个调试技巧,当我从您那里得到数据后,我大概花了五分钟来分析。我所做的就是对两个字符串调用json.loads并读取错误消息。从底层做起,再往上爬总是值得的。:-)

相关问题 更多 >

    热门问题