在 Python 中有效地解析 JSON 输出?

Parsing JSON output efficiently in Python?

下面的代码块有效,但由于我对使用 JSON 的理解有限,我不满意它是最佳的,但我似乎无法找到更有效的方法。

steam_game_db是这样的:

{
    "applist": {
        "apps": [
            {
                "appid": 5,
                "name": "Dedicated Server"
            },
            {
                "appid": 7,
                "name": "Steam Client"
            },
            {
                "appid": 8,
                "name": "winui2"
            },
            {
                "appid": 10,
                "name": "Counter-Strike"
            }
        ]
    }
}

我的 Python 代码是

i = 0
x = 570

req_name_from_id = requests.get(steam_game_db)
j = req_name_from_id.json()

while j["applist"]["apps"][i]["appid"] != x:
    i+=1
returned_game = j["applist"]["apps"][i]["name"]
print(returned_game)

有没有更智能的方法来搜索它,而不是遍历整个应用列表?理想情况下,数据结构中具有 'appid' 和 'name' 的元素的编号与其对应的 'appid'

相同

即 列表中appid 570为Dota2 然而,appid 5069 和 Red Faction

中数据结构中的元素 570

请问这是什么类型的数据结构?也许它已经限制了我对这个答案的搜索能力。 (也就是说,对我来说每个元素都像是 'appid' 和 'element' 的字典?)

编辑:已按照建议更改为 for 循环

# returned_id string for appid from another query

req_name_from_id = requests.get(steam_game_db)
j_2 = req_name_from_id.json()

for app in j_2["applist"]["apps"]:
    if app["appid"] == int(returned_id):
        returned_game = app["name"]

print(returned_game)

通过密钥(如此处的应用程序 ID)访问内容的最便捷方式是使用字典。

您预先支付了一些额外的性能成本来填充字典,但之后通过 ID 提取值基本上是免费的。

但是,这是一种权衡。如果您只想在 Python 程序的生命周期内进行一次查找,那么与像您已经做过的简单循环相比,支付额外的性能成本来构建字典不会有任何好处.但如果你想进行多次查找,这将是有益的。

# build dictionary
app_by_id = {}
for app in j["applist"]["apps"]:
  app_by_id[app["appid"]] = app["name"]

# use it
print(app_by_id["570"])

还要考虑在磁盘上缓存 JSON 文件。这将在您的程序启动期间节省时间。

最好将 JSON 文件放在磁盘上,您可以直接将其转储到字典中并开始构建您的 lookup table。例如,我试图在使用 dict 进行查找时维护您的逻辑。不要忘记对其中包含特殊字符的 JSON 进行编码。

设置:

import json

f = open('bigJson.json')

apps = {}
with open('bigJson.json', encoding="utf-8") as handle:
    dictdump = json.loads(handle.read())

    for item in dictdump['applist']['apps']:
        apps.setdefault(item['appid'], item['name'])

用法 1: 你就是这样用的

for appid in range(0, 570):
    if appid in apps:
        print(appid, apps[appid].encode("utf-8"))

用法 2:这就是查询键的方式,使用 get 而不是 [] 将防止 KeyError 异常appid 没有记录。

print(apps.get(570, 0))