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.