-1

New to both so here goes.

I am accessing an api using requests.get that returns an array with clubs and the number of active clubs.

clubs = requests.get ('https://api.sumting.com/so on/and so forth', headers={'Authorization': myToken})

clubdata = clubs.json()
print (clubdata)

I get something like this:

{
  "clubs": [
    {
      "golf_association_id": 1,
      "club_number": 2,
      "club_name": "Otterkill Golf & Country Club",
      "phone": "8454272020",
      "is_dac": false,
      "technology_provider": "Nope",
      "email": "",
      "authorized": null,
      "is_test": false,
      "status": "Active",
      "club_category": "Private",
      "short_name": "",
      "website": "",
      "usga_version": "",
      "handicap_chairperson": "",
      "date": "2019-08-13T14:06:55.928Z",
      "created_at": "2019-08-13T14:06:55.928Z",
      "updated_at": "2019-08-13T14:06:55.928Z",
      "logo": null,
      "club_type": "",
      "alt_text": null,
      "id": 10001,
      "city": "Campbell Hall",
      "state": "NY"
    }
  ],
  "meta": {
    "active_clubs_count": 548
  }
}

I need to loop through the "id"s and call another api. The latest of several things I have tried is this:

clubs = requests.get ('https://api.sumting.com/so on/and so forth', headers={'Authorization': myToken})

clubdata = clubs.json()
##print (clubdata)

decoded = json.loads(clubdata)

# Access data
for x in decoded['id']:
    print (x['club_name'])

Which results in this:

Traceback (most recent call last): File "C:\Program Files (x86)\Python38-32\Scripts\test-login.py", line 28, in decoded = json.loads(clubdata) File "C:\Program Files (x86)\Python38-32\lib\json__init__.py", line 341, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not dict

I clearly do not understand what I need to understand but have come this far and I am hoping a gentle nudge in the right direction will help me continue down the road.

Thanks in advance.

  • Why are you passing the result of `clubs.json()` to `json.loads()` ? – AMC Mar 10 '20 at 01:10
  • Does this answer your question? [python JSON object must be str, bytes or bytearray, not 'dict](https://stackoverflow.com/questions/42354001/python-json-object-must-be-str-bytes-or-bytearray-not-dict) – AMC Mar 10 '20 at 01:11

1 Answers1

0

It looks like maybe you aren't grabbing the proper part of the JSON. Before you do the loop, try printing out the clubs key (since the response returns a key named "clubs"), e.g.

print(decoded['clubs']) # <-- does this show you the list?  

If the above shows an error, then figure out why. E.g. what does print(decoded.keys()) return? If the above shows you the list of clubs, then you can loop over it, e.g.

for x in decoded['clubs']:
    print (x['club_name'])

I hope that helps!

Everett
  • 8,746
  • 5
  • 35
  • 49