2

I'm pretty new to Python so forgive me here.

I'm trying to call/print/log JSON from a GET request. I need to get the id's following this tree: items > track > artists > id.

Basically im trying to just get the ID's from each track on this JSON file/list. I keep getting errors no matter how I format them. Again im new so im not sure how to call it let also run it in a loop to get all the ID's as an array. I have done it with other JSON files in the past but this one is farther in and I get the error : TypeError: list indices must be integers or slices, not str

I figured out it works when you do it by adding the [0] like this: artists = response["items"][0]["track"]["artists"] BUT I want to loop it and get all of the Id's for each one and that option picks just one.

here is the beginning of the json so you can see the layout.


{
  "href": "https://api.spotify.com/v1/me/tracks?offset=0&limit=15&market=US", 
  "items": [
    {
      "added_at": "2021-12-15T22:26:25Z", 
      "track": {
        "album": {
          "album_type": "single", 
          "artists": [
            {
              "external_urls": {
                "spotify": "https://open.spotify.com/artist/6MlPT0WxdWnrYcpXT8GZF8"
              }, 
              "href": "https://api.spotify.com/v1/artists/6MlPT0WxdWnrYcpXT8GZF8", 
              "id": "6MlPT0WxdWnrYcpXT8GZF8", 
              "name": "PARKFORD", 
              "type": "artist", 
              "uri": "spotify:artist:6MlPT0WxdWnrYcpXT8GZF8"
            }
          ], 
          "external_urls": {
            "spotify": "https://open.spotify.com/album/4o2d8uBTyMfJeaJqSXn9tP"
          }, 
          "href": "https://api.spotify.com/v1/albums/4o2d8uBTyMfJeaJqSXn9tP", 
          "id": "4o2d8uBTyMfJeaJqSXn9tP", 
          "images": [
            {
              "height": 640, 
              "url": "https://i.scdn.co/image/ab67616d0000b27332bcd9e1b2234c6cd6b2b2ec", 
              "width": 640
            }, 
            {
              "height": 300, 
              "url": "https://i.scdn.co/image/ab67616d00001e0232bcd9e1b2234c6cd6b2b2ec", 
              "width": 300
            }, 
            {
              "height": 64, 
              "url": "https://i.scdn.co/image/ab67616d0000485132bcd9e1b2234c6cd6b2b2ec", 
              "width": 64
            }
          ], 
          "name": "There's Nothing in the Rain", 
          "release_date": "2021-11-25", 
          "release_date_precision": "day", 
          "total_tracks": 1, 
          "type": "album", 
          "uri": "spotify:album:4o2d8uBTyMfJeaJqSXn9tP"
        }, 
        "artists": [
          {
            "external_urls": {
              "spotify": "https://open.spotify.com/artist/6MlPT0WxdWnrYcpXT8GZF8"
            }, 
            "href": "https://api.spotify.com/v1/artists/6MlPT0WxdWnrYcpXT8GZF8", 
            "id": "6MlPT0WxdWnrYcpXT8GZF8", 
            "name": "PARKFORD", 
            "type": "artist", 
            "uri": "spotify:artist:6MlPT0WxdWnrYcpXT8GZF8"

here is the code I have written out

 uri = MY_LIKED_SONGS
    headers = {
        "Authorization": f'Bearer {tokens["access_token"]}',
        "Content-Type": "application/json",
    }
    r = requests.get(uri, headers=headers)
    response = r.json()
    # return response
    artist_ids = {}

    data = json.dumps(response)
    for artist_ids in data["items"]["track"]:
        logger.info(artist_ids["items"]["track"]["artists"]["id"])
        print(artist_ids["_source"]["items"][0]["track"]["id"])

    tracks = response["items"]["track"][0]["artists"]["id"] 
4
  • Can you please include the exact error message? Thanks. Commented Dec 28, 2021 at 3:57
  • I keep getting errors Don't make us guess what the errors are. Commented Dec 28, 2021 at 4:16
  • sorry I was still typing them out trying to be thorough. it's updated now with more info Commented Dec 28, 2021 at 4:20
  • If @ForamJ's answer is right and help you solve your problem. Please, accept it or vote up. Commented Jan 5, 2022 at 1:24

1 Answer 1

1

Here when you do json.dumps(), it converts a Python object into a json string. In order to iterate through json object you need to convert it into json object. For that you have to use json.loads() then you can get artist id from that.


data = json.loads(json.dumps(response))

for item in data["items"]:
  for artist in item['track']['album']['artists']:
    print(artist['id'])

This might be helpful.

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

1 Comment

thank you!! That worked, and I learned why. I appreciate it!

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.