1

I am working on a discord bot that gets information from an API. For this command I want to return some information, and display it nicely for the user. This is the code (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)

Screenshot of the API response with input if I write it to a file *clan 500075680: https://i.sstatic.net/GQlvA.jpg

When I run this code:

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

I get this in console:

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."}

So the key clan_id (which is a input argument that changes) has multiple values.

My question is, if I take the clan_id = 500075680 for example, how do I display from value 'name': 'Reloading', Reloading individually? How can I define the variables in my code?

Fixed it thanks to you guys:

I had the clan_id argument specified as an integer, removing that makes it work: clan_name = repository[clan_id]['name']

3
  • I'm a little confused as to what you are looking for but it sounds like you want to access a nested JSON key which can be done like this -> repository['500075680']['name'] Commented Jul 21, 2020 at 14:57
  • that number is a variable, if I do clan_name = repository[clan_id]['name'] and then try to print clan_name, it gives me Command raised an exception: KeyError: 500075680 Commented Jul 21, 2020 at 15:07
  • Look at the answers. You can loop through the top level keys instead of specifying them. If you only want 1 key with a specific value, use a try except block to loop through and print only the ones you want. Commented Jul 21, 2020 at 15:18

3 Answers 3

2

Assuming value is dictionary
to acess the value of name from value dictionary use value['name']

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

from the image you shared, you can get the value of name by using this repository['data'][key]['name']

if there are list of responses
example: repository=[{key1:{'name':name1}},{key2:{'name':name2}}

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

repository is a list holding all responses

Sign up to request clarification or add additional context in comments.

7 Comments

clan_name = repository['data'][clan_id]['name'] or clan_name = repository['data'][key]['name'] (and then printing that) gives me Command raised an exception: KeyError: 'data' again.
repository['key']['name'] use this this should give the result make sure key is string
Command raised an exception: KeyError: 'key' again
{'500075680': {'members_count': 81, 'name': 'Reloading', 'color': '#B80909', 'leader_name': 'Joc666', 'emblems': {'x256': {'wowp': 'eu.wargaming.net/clans/media/clans/emblems/cl_680/500075680/…'}}, 'tag': '-RLD-', 'motto': "In the end, we only regret the chances we didn't take."}}
print(repository['500075680']['name']) check this
|
1

Try using json.loads().

For example to get the value of name you could parse your json into a python dict and retrieve it from there.

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

1 Comment

I am not actually writing the api response in a json file, that was just to explain what a response could be.
0

Here is another nice way to do it.

json_object = json.loads(json_response)
formatted_data = json.dumps(json_object, indent=2)
print(formatted_data)

json.dumps method with indent will formate it and you can controle the formatting with indent value.

It is equivalent to PHP array formatting after converting JSON to an array.

echo "<pre>";
print_r()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.