【问题标题】:Display data from json with discord.py使用 discord.py 显示来自 json 的数据
【发布时间】:2016-11-08 23:21:27
【问题描述】:

我目前正在制作一个显示 osu 的不和谐机器人!统计数据。这是我的代码:

@bot.command()
async def osu(osu_name : str):
    """Adds two numbers together."""
    await bot.say("Fetching data")
    url = 'https://osu.ppy.sh/api/get_user?k={ my api key }&u=' + osu_name
    # Do the HTTP get request
    response = requests.get(url, verify=True) #Verify is check SSL certificate
    # Decode the JSON response into a dictionary and use the data
    await bot.say(response.json())

osu! api 在它的 json 中给出了这个:

[{
    "user_id"      : "1",
    "username"     : "User name",
    "count300"     : "1337",      // Total amount for all ranked and approved beatmaps played
    "count100"     : "123",       // Total amount for all ranked and approved beatmaps played
    "count50"      : "69",        // Total amount for all ranked and approved beatmaps played
    "playcount"    : "42",        // Only counts ranked and approved beatmaps
    "ranked_score" : "666666",    // Counts the best individual score on each ranked and approved beatmaps
    "total_score"  : "999999998", // Counts every score on ranked and approved beatmaps
    "pp_rank"      : "2442",
    "level"        : "50.5050",
    "pp_raw"       : "3113",
    "accuracy"     : "98.1234",
    "count_rank_ss": "54",
    "count_rank_s" : "81",        // Counts for SS/S/A ranks on maps
    "count_rank_a" : "862",    
    "country"      : "DE",        // Uses the ISO3166-1 alpha-2 country code naming. See this for more information: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2/wiki/ISO_3166-1_alpha-2)
    "pp_country_rank":"1337",     // The user's rank in the country.
    "events"       : [{           // Contains events for this user
        "display_html"  : "<img src='\/images\/A_small.png'\/>...",
        "beatmap_id"    : "222342",
        "beatmapset_id" : "54851",
        "date"      : "2013-07-07 22:34:04",
        "epicfactor"    : "1"      // How "epic" this event is (between 1 and 32)
    }, { ... }, ...]
}]

我的代码在不和谐中这样显示

我只想展示 json 中的一些东西,例如“pp_raw”、“level”、“accuracy”等。

【问题讨论】:

  • 好的,所以只打印 JSON 的一部分。您可以像访问任何其他字典一样访问它。
  • 这不太准确。

标签: python json python-3.x bots


【解决方案1】:

data = response.json() 返回字典对象的列表。因此,您必须在访问值之前先指定索引。假设您要访问第一个对象中的pp_raw,它将如下所示:

print data[0]['pp_raw']

【讨论】:

    【解决方案2】:

    您可以使用 python 的内置 json 模块将 json 响应转换为 python 字典 - 只需 import json 然后执行类似的操作来访问响应的各个元素:data = json.loads(response.json())[0]。然后,您可以访问诸如 data['pp_raw'] 之类的单个元素,并以您认为合适的方式显示它们。

    【讨论】:

    • 你能给我一个sn-p吗?
    • 我添加data = json.loads(response.json()) await bot.say(data['pp_raw'])时没有显示数据
    • 对不起,我错过了响应是一个列表。现在编辑。
    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多