Showing posts with label urllib. Show all posts
Showing posts with label urllib. Show all posts

Wednesday, July 31, 2013

Reading from a JSON Dictionary



Dictionaries are useful data structures, and at their core, are a set of one-to-one mappings of data.

A loop and append pattern should work fine for getting the data into the dictionary.

(Of course using the JSON library would greatly simplify this process.)


from urllib.request import urlopen

html = urlopen("http://www.leafly.com/api/strains")

theDataArray = str(html.read()).split('},{')

dictionary = {}

for i in range(100):

      dictionary[theDataArray[i].split(',')[1].split('"')[3]] = theDataArray[i].split(',')[2].split('"')[3]

That last line might look like a lot, but it's mostly just parsing away all the commas and other characters to get at the two pieces of information we're going for, key and name.

This will also take in only 100 strains, for all change to 100 to len(theDataArray), just remember to properly parse the data to avoid errors.

Monday, July 29, 2013

Reading API Data



In Python, this is as easy as running a couple of commands in IDLE.

from urllib import urlopen

html = urlopen("http://www.leafly.com/api/details/100-og")

html.read() 


HTTPResponse instances also have some more methods and attributes, which can be found here: http://docs.python.org/release/2.2.3/lib/httpresponse-objects.html


This can be additionally simplified by importing and using the json library.