Accessing Json data (I think I am nearly there) complete beginner

Andrew Edwards-Adams aeaprog at gmail.com
Thu May 23 12:09:31 EDT 2013


Hey guys
I think its worth stating that I have been trying to code for 1 week. 
I am trying to access some Json data. My innitial code was the below: 

"import mechanize
import urllib
import re
 
def getData():  
    post_url = "http://www.tweetnaps.co.uk/leaderboards/leaderboard_json/all_time"
    browser = mechanize.Browser()
    browser.set_handle_robots(False)
    browser.addheaders = [('User-agent', 'Firefox')]
 
    #These are the parameters you've got from checking with the aforementioned tools
    parameters = {'page' : '1',
                  'rp' : '10',
                  'sortname' : 'total_pl',
                  'sortorder' : 'desc'}
    #Encode the parameters
    data = urllib.urlencode(parameters)
    trans_array = browser.open(post_url,data).read().decode('UTF-8')
 
    #print trans_array

    myfile = open("test.txt", "w")
    myfile.write(trans_array)
    myfile.close()

getData()
 
raw_input("Complete")"

I was recommended to use the following code to access the Json data directly, however I cannot get it to return anything. I think the guy that recommended me this method must have got something wrong? Or perhaps I am simply incompetent: 

import mechanize
import urllib
import json
def getData():  
    post_url = "http://www.tweetnaps.co.uk/leaderboards/leaderboard_json/current_week"
    browser = mechanize.Browser()
    browser.set_handle_robots(False)
    browser.addheaders = [('User-agent', 'Firefox')]
 
    #These are the parameters you've got from checking with the aforementioned tools
    parameters = {'page' : '1',
                  'rp' : '50',
                  'sortname' : 'total_pl',
                  'sortorder' : 'desc'
                 }
    #Encode the parameters
    data = urllib.urlencode(parameters)
    trans_array = browser.open(post_url,data).read().decode('UTF-8')
 
    text1 = json.loads(trans_array)
    print text1['rows'][0]['id']  #play around with these values to access different data..
   
getData()

He told me to "#play around with these values to access different data.." really cant get anything out of this, any ideas? 

Many thanks AEA



More information about the Python-list mailing list