如何使用python正确格式化请求API json响应?

2024-05-29 02:58:54 发布

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

我正在开发一个discord机器人,它从API获取信息。对于这个命令,我想返回一些信息,并为用户很好地显示它。以下是代码(Python 3.8.3,discord.py):

import json
import requests
import discord

@bot.command(name="clan")
async def clan_command(ctx, clan_id:int):

    response = requests.get(f'https://api.worldoftanks.eu/wot/clans/info/?application_id=0a833f3e275be2c9b458c61d6cedf644&clan_id={clan_id}&fields=leader_name%2C+members_count%2C+tag%2C+motto%2C+name%2C+emblems.x256%2C+color', params={'q': 'requests+language:python'})
    json_response = response.json()
    repository = json_response["data"]

    clan_name = 
    clan_colour = 
    clan_url = f"https://eu.wargaming.net/clans/wot/{clan_id}/"
    clan_logo = 
    clan_commander = 
    clan_member_count = 
    clan_tag = 
    clan_motto = 

    embed = discord.Embed(title=clan_name (clan_tag), colour=clan_colour, url=clan_url)
    embed.set_thumbnail(url=clan_logo)
    embed.add_field(name="Commander:", value=clan_commander, inline=True)
    embed.add_field(name="Member count:", value=clan_member_count, inline=True)
    embed.add_field(name="Clan motto:", value=clan_motto, inline=True)

    await ctx.channel.send(embed=embed)

如果将API响应写入文件*clan 500075680:https://imgur.com/a/BzkctRP,则该API响应的屏幕截图包含输入

当我运行此代码时:

for key, value in repository.items():
    print(f"key {key} has value {value}")

我在控制台中看到:

key 500075680 has value {'members_count': 81, 'name': 'Reloading', 'color': '#B80909', 'leader_name': 'Joc666', 'emblems': {'x256': {'wowp': 'https://eu.wargaming.net/clans/media/clans/emblems/cl_680/500075680/emblem_256x256.png'}}, 'tag': '-RLD-', 'motto': "In the end, we only regret the chances we didn't take."}

因此键clan_id(这是一个改变的输入参数)有多个值

我的问题是,如果以clan_id=500075680为例,我如何从值'name'显示:“重新加载”,单独重新加载? 如何在代码中定义变量

多亏了你们才修复了它:

我将clan_id参数指定为一个整数,删除它可以使其工作: clan_name = repository[clan_id]['name']


Tags: keynamehttpsapiidjsonurlvalue
2条回答

假设值为字典
要从值字典访问name的值,请使用value['name']

for key, value in repository.items():
    print(f"key {key} has value {value['name']}")

从您共享的图像中,您可以使用以下repository['data'][key]['name']获取name的值

如果有响应列表
例子: repository=[{key1:{'name':name1}},{key2:{'name':name2}}

for item in repository:
    key=next(iter(item))
    print(item[key]['name'])

repository是一个包含所有响应的列表

尝试使用json.loads()

例如,要获取name的值,可以将json解析为python dict并从中检索它

for key, value in repository.items():
    value_dict = json.loads(value)
    print(value_dict["name"])

相关问题 更多 >

    热门问题