How to properly format requests API json response with python?

Question:

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://imgur.com/a/BzkctRP

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']

Asked By: Buster

||

Answers:

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"])
Answered By: akopyl

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

Answered By: user13966865

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()
Answered By: Qaisar Shabbir
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.