-1

Since I just started with Python, I have some difficulties with accessing the keys.
I want to loop through each Foursquare venue I got as an JSON response, to get the Venue ID. The Venue ID then should be added as a parameter to get all the details to the venues.

I already tried it with a for loop, but it did not work:

for a in data['response']['groups']['items']['venue']:
my_place_id = place['id']

venue_ID_resp = requests.get(url=url_venue_details,params=my_place_id)

Error messsage:

for a in data['response']['groups']['items']['venue']:
TypeError: list indices must be integers or slices, not str

The response looks like this:

'response':{  
   'groups':[  
      {  
         'items':[  
            {  
               'reasons':{  
                  'count':0,
                  'items':[  
                     {  
                        'reasonName':'globalInteractionReason',
                        'summary':'This '                        'spot '                        'is '                        'popular',
                        'type':'general'
                     }
                  ]
               },
               'referralId':'e-0-52bf5eca498e01893b7004fb-0',
               'venue':{  
                  'categories':[  
                     {  
                        'icon':{  
                           'prefix':'https://ss3.4sqi.net/img/categories_v2/travel/hostel_',
                           'suffix':'.png'
                        },
                        'id':'4bf58dd8d48988d1ee931735',
                        'name':'Hostel',
                        'pluralName':'Hostels',
                        'primary':True,
                        'shortName':'Hostel'
                     }
                  ],
                  'id':'52bf5eca498e01893b7004fb',
                  'location':{  

I only want to get the Venue ID, like:

print(my_place_id)

4bf58dd8d48988d1ee931234
4bf58dd8d48988d1ee945225
4bf58dd8d48988d1ee931888
4bf58dd8d48988d1ee564563
.
.
.
funie200
  • 3,688
  • 5
  • 21
  • 34

2 Answers2

0

items inside group in your response JSON is a list. This is the reason you get the error: " TypeError: list indices must be integers or slices, not str" as list index cannot be a string.

As correctly pointed out by @tfw, even groups is a list, so it should be

You need to access it as data['response']['groups'][0]['items'][0]['venue']

If there are going to multiple elements in the items list, then better to loop through them and access like below

for x in data['response']['groups']:
    for y in x['items']
        print y['venue']
Jay
  • 24,173
  • 25
  • 93
  • 141
0

Your Json contains lists. You can get id:

my_id = data['response']['groups']['items'][0]['venue']['categories'][0]['id']

Note: If you have more elements in your lists, you can create for loop and get all ID.

milanbalazs
  • 4,811
  • 4
  • 23
  • 45