0
  @commands.command()
  async def np(self,ctx):
        async with aiohttp.ClientSession() as session:
            params= {"api_key" : "censored",
            "user" : "ssj4abd",
            "period" : "overall",
             "limit" : 10,
             "method":"user.getTopArtists",
             "format":"json"}
            async with session.get(url="http://ws.audioscrobbler.com/2.0", params=params) as response:
                resp = await response.read()
                print(resp)

I am making it so that it retrieves the top (1st) artist of a user, the reply is something really long which you can find here. How do I retrieve/fetch only the "rank" : 1 artist from all that mess?

SSJ4 ABD
  • 15
  • 6

1 Answers1

1

You're requesting a JSON response

"format":"json"}

So this is what you get. To load it into a dictionary, use the json library

import json
jsonData = json.loads(resp)

Now, you can get the dictionary for the first artist via

topArtist = jsonData["topartists"]["artist"][0]

And from there, you can retrieve all the info, like the url

topArtistUrl = topArtist["url"]

import json
@commands.command()
  async def np(self,ctx):
        async with aiohttp.ClientSession() as session:
            params= {"api_key" : "censored",
            "user" : "ssj4abd",
            "period" : "overall",
             "limit" : 10,
             "method":"user.getTopArtists",
             "format":"json"}
            async with session.get(url="http://ws.audioscrobbler.com/2.0", params=params) as response:
                resp = await response.read()
                jsonData = json.loads(resp)
                topArtist = jsonData["topartists"]["artist"][0]
                topArtistUrl = topArtist["url"]
itzFlubby
  • 2,269
  • 1
  • 9
  • 31
  • [this](https://media.discordapp.net/attachments/853563123147079691/855074157083099176/unknown.png?width=694&height=462) is the response, im confused on the extracting just the first artists name part – SSJ4 ABD Jun 17 '21 at 13:20
  • 1
    Well, if you want to get the name use `topArtist["name"]`. Or in short: `jsonData["topartists"]["artist"][0]["name"]` – itzFlubby Jun 17 '21 at 13:23
  • 1
    @SSJ4ABD He's already given you an answer. Did you even read it? Replace `topArtistUrl = topArtist["url"]` with `topArtistName = topArtist["name"]`. – aneroid Jun 17 '21 at 13:23
  • @SSJ4ABD If that helped, read: [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers), and about [accepting](https://meta.stackexchange.com/a/5235/193893) and [voting](https://stackoverflow.com/privileges/vote-up). – aneroid Jun 17 '21 at 14:48