JSON confusion

Steve Simmons square.steve at gmail.com
Wed Aug 17 12:35:36 EDT 2016


I'm trying to write a small utility to find the closest railway station 
to a given (UK) postcode but the result is in JSON and I'm not familiar 
with it. I've got as far as extracting the JSON object and I can print 
the first level elements ("success" and "result") but I've totally 
confused myself about how to delve into the rest of the data structure. 
Can anyone point me to a 'how-to' for tackling a fairly complex SJON 
object or give me some pointers. ... or maybe point out if I'm taking an 
unnecessarily complex approach. Initially, I'm Looking to extract 
'stationname', 'distance' and one or two of the coordinate pairs. To be 
honest, I'd rather have some hints rather than the whole solution 
otherwise I'll not learn anything :-) SteveS def main():
     import urllib
     import urllib.request
     import urllib.parse
     import urllib.response
     import json

     url ='https://data.gov.uk/data/api/service/transport/naptan_railway_stations/postcode?postcode=CT16+1ez&distance=2' 
req = urllib.request.urlopen(url)

     req_json = req.read()
     str_json = req_json.decode("utf-8")

     p_json = json.loads(str_json)
     print(p_json)
     print ('======================================')
     print(repr(p_json))
     print('SUCCESS: ',repr(p_json['success']))
     print ('======================================')
     print('RESULT : ',repr(p_json['result']))

if __name__ =="__main__":
     main()




More information about the Python-list mailing list