我正在开发一个从API获取信息的discord bot。 对于这个命令,我希望返回一些信息,并为用户良好地显示这些信息。 这是代码(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)
如果我将其写入文件*clan500075680
: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."}
因此键input_id有多个值。 我的问题是,如何从值“name”显示:“Reloading”例如,单独地重新加载? 那么如何定义代码中的变量呢?
尝试使用json.loads()。
例如,要获取name
的值,可以将json解析为python dict并从那里检索它。
for key, value in repository.items():
value_dict = json.loads(value)
print(value_dict["name"])
假设value是dictionary
要从value dictionary中访问name的值,请使用value['name']
for key, value in repository.items():
print(f"key {key} has value {value['name']}")
从您共享的图像中,您可以使用此repository['data'][key]['name']
获取name的值