简体   繁体   English

使用python从api导出特定的json数据

[英]Exporting specific json data from api with python

First time here, I am making a small discord.py bot as a project to experiment with python/apis a little.第一次来这里,我正在制作一个小的 discord.py 机器人作为一个项目来试验一下 python/apis。 My goal is to print in discord specific data from an api when asked.我的目标是在被问到时从 api 打印不和谐的特定数据。 here is the code in question.这是有问题的代码。

@client.command()
async def otherusers(ctx, player):
    rs = requests.get(apiLink + "/checkban?name=" + str(player))
    if rs.status_code == 200:
        rs = rs.json()
        embed = discord.Embed(title="Other users for" + str(player), description="""User is known as: """ + str(rs["usedNames"]))
        await ctx.send(embed=embed)

here is an example of the API request这是 API 请求的示例

{"id":1536171865,"avatar":"https://secure.download.dm.origin.com/production/avatar/prod/userAvatar/41472001/208x208.PNG","name":"_7cV","vban":{"A1 Army of One":{"bannedUntil":null,"reason":"ping >1000"}},"ingame":[],"otherNames":{"updateTimestamp":"2022-07-08T10:10:50.939000","usedNames":["ABCDE123","ABCDE1234","ABCDE12345","ABCDE1234567"]}}

If I change the string to str(rs["otherNames"]) it does function but I would like to only include the usernames, if I put str(rs["usedNames"]) and request on discord it gives me an error on PyCharm.如果我将字符串更改为str(rs["otherNames"])它确实起作用,但我只想包含用户名,如果我将str(rs["usedNames"])和请求放在不和谐上,它会给我一个错误PyCharm。

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'usedNames' discord.ext.commands.errors.CommandInvokeError:命令引发异常:KeyError:'usedNames'

Thanks in advance :)提前致谢 :)

Alright so as far as I can tell, the return from your API request where the "usedNames" key is located is nested.好吧,据我所知, "usedNames"键所在的 API 请求的返回是嵌套的。 Try:尝试:

str(rs["otherNames"]["usedNames"])

I should note this will return ["ABCDE123","ABCDE1234","ABCDE12345","ABCDE1234567"] in the example which you gave.我应该注意这将在您给出的示例中返回["ABCDE123","ABCDE1234","ABCDE12345","ABCDE1234567"] You might want to format the list of other usernames for your final product.您可能希望为最终产品格式化其他用户名列表。

I hope that helped:)我希望这有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM