facebook – Python 2.7.6, KeyError: data when trying to run script

facebook – Python 2.7.6, KeyError: data when trying to run script

You probably just dont have a JSON field for data in test2.txt

KeyError means that there is no such key in a dict object. Therefore it means your file does not contain JSON data structure like this according to your script.

{data: {id: 10000}, {id: 20000}, {id: 30000}}

It would help if you posted the contents of test2.txt or the output of print(data).

Edit: according to your text2.txt file, your program flow should be like this

for user in data[members][data]:
    print user
    page = urlopen(http://graph.facebook.com/ + user[id] + ?fields=picture)
    page_data = json.loads(page.read())
    photo_url = page_data[picture][data][url]
    user_photos[user[id]] = [user[name], photo_url]

You just simply change data[data] to data[members][data] to make your script work.

facebook – Python 2.7.6, KeyError: data when trying to run script

Looking at the docs, you should have exactly the same structure as the following in your txt file bar the details.

{
  data: [
    {
      name: Arushi Jain, 
      administrator: false, 
      id: 100000582289046
    }, 
    {
      name: Ajay Yadav, 
      administrator: false, 
      id: 100004213058283
    }, 
    and so on ........

  ], 
  paging: {
    next: https://graph.facebook.com/114462201948585/members?limit=5000&offset=5000&__after_id=712305377
  }
}

{

 {
  data: [                    # how yours should look
   {
        name: Patryk Wiśniewski,
        administrator: false,
        id: 321297624692717
      },
      {
        name: Patryk Kurowski,
        administrator: false,
        id: 1429534777317507
      },
      {
        name: Jan Konieczny,
        administrator: false,
        id: 852450774783365
      }

  ], 
  paging: {
    next: https://graph.facebook.com/114462201948585/members?limit=5000&offset=5000&__after_id=712305377
  }
}

That is the very first thing that is executed in the loop so if it does not match exactly then it will fail as it does in your error.

Leave a Reply

Your email address will not be published. Required fields are marked *