【问题标题】:Retrieve specific data from JSON file in Python在 Python 中从 JSON 文件中检索特定数据
【发布时间】:2022-01-01 14:54:40
【问题描述】:

大家好,新年快乐!我第一次在这里发帖,因为我找不到我的问题的答案,我已经搜索了 2 天,不知道该怎么做,这让我发疯......这是我的问题:

我正在使用Steamspy api 下载过去两周在 Steam 上玩得最多的 100 款游戏的数据,我能够将下载的数据转储到 .json 文件中(在这种情况下为 dumped_data.json ),并将其导入到我的 Python 代码中(我可以打印它)。虽然我可以打印整个内容,但它并不是真正有用的,因为它有 1900 行或多或少有用的数据,所以我希望能够只打印转储数据的特定项目。在这个项目中,我只想打印列表中前 10 款游戏的名称、开发商、所有者和价格。这是我的第一个 Python 项目,我不知道该怎么做……

这是 Python 代码:

import steamspypi
import json

#gets data using the steamspy api
data_request = dict()
data_request["request"] = "top100in2weeks"

#dumps the data into json file
steam_data = steamspypi.download(data_request)
with open("dumped_data.json", "w") as jsonfile:
    json.dump(steam_data, jsonfile, indent=4)

#print values from dumped file
f = open("dumped_data.json")
data= json.load(f)

print(data)

以下是 json 文件中第一项的示例:

{
"570": {
    "appid": 570,
    "name": "Dota 2",
    "developer": "Valve",
    "publisher": "Valve",
    "score_rank": "",
    "positive": 1378093,
    "negative": 267290,
    "userscore": 0,
    "owners": "100,000,000 .. 200,000,000",
    "average_forever": 35763,
    "average_2weeks": 1831,
    "median_forever": 1079,
    "median_2weeks": 1020,
    "price": "0",
    "initialprice": "0",
    "discount": "0",
    "ccu": 553462
},

提前感谢所有愿意帮助我的人,这意义重大。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我知道这有点笨,但我尝试了一些基本的东西,例如:“print(data[0])”至少获得列表的第一个游戏,这当然没有用...然后我尝试“print(data["570"] ["name"] ["appid"])" 获取第一个游戏的名称和appid,输出错误“TypeError:字符串索引必须是整数"
  • data["570"]["name"] 是一个字符串,在本例中为"Dota 2"
  • 哦,所以我需要将文件中的每个字符串都转换为整数?
  • 不,您不能使用另一个字符串为字符串值下标。想想看,"Dota 2"["appid"] 到底是什么意思?

标签: python json api


【解决方案1】:

以下打印出您希望从前 10 场比赛中获得的值:

for game in list(data.values())[:10]:
    print(game["name"], game["developer"], game["owners"], game["price"])

【讨论】:

  • 非常感谢!这正是我需要的,你是救生员!
猜你喜欢
  • 2017-01-26
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多