Advertisement
cymplecy

final

Feb 7th, 2017
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import urllib2
  3. import json
  4.  
  5.  
  6. class GetJSONFromURL():
  7.     def __init__(self):
  8.         self.lastID = 0
  9.  
  10.     def flatten_dict(self,dd, separator='_', prefix=''):
  11.         return { prefix + separator + k if prefix else k : v
  12.                  for kk, vv in dd.items()
  13.                  for k, v in self.flatten_dict(vv, separator, kk).items()
  14.                  } if isinstance(dd, dict) else { prefix : dd }        
  15.        
  16.     def parse_dict(self,init, lkey=''):
  17.         ret = {}
  18.         for rkey,val in init.items():
  19.             key = lkey+rkey
  20.             if isinstance(val, dict):
  21.                 ret.update(self.parse_dict(val, key+'_'))
  22.             #  This bit added in to deal with elements of JSON that are lists
  23.             elif isinstance(val, list):
  24.                 for listitem in val:
  25.                     ret.update(self.parse_dict({key + str(val.index(listitem)) : listitem},  ''))
  26.             #  end of my addition following your prompt :)
  27.             else:
  28.                 ret[key] = val
  29.         return ret
  30.  
  31.     # retrieve and load the JSON data into a JSON object
  32.     def getJSON(self, url):
  33.         jdata = '{"coord":{"lon":-2.62,"lat":53.65},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09n"},{"id":741,"main":"Fog","description":"fog","icon":"50n"}],"base":"stations","main":{"temp":277.14,"pressure":1009,"humidity":100,"temp_min":276.15,"temp_max":278.15},"visibility":10000,"wind":{"speed":5.1,"deg":160},"clouds":{"all":40},"dt":1486450200,"sys":{"type":1,"id":5098,"message":0.0029,"country":"GB","sunrise":1486453471,"sunset":1486487131},"id":2653086,"name":"Chorley","cod":200} '
  34.        
  35.         feedData = jdata
  36.         #jsonFeed = urllib2.urlopen(url)
  37.         #feedData = jsonFeed.read()
  38.         #print feedData
  39.         #jsonFeed.close()
  40.         data = json.loads(feedData)
  41.         #return self.parse_dict(data)
  42.         return self.parse_dict(data)
  43.        
  44. j=GetJSONFromURL()
  45.  
  46. msg = j.getJSON("test")
  47.  
  48. for x in msg.items():
  49.     print x
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement