On 8/17/2016 12:35 PM, Steve Simmons wrote:
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
add   import pprint


    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)

This result is nexted dicts and lists

    print(p_json)
    print ('======================================')
    print(repr(p_json))
    print('SUCCESS: ',repr(p_json['success']))
    print ('======================================')
    print('RESULT : ',repr(p_json['result']))

Replace prints above with
pprint.pprint(p_json)
and you will see the better formatted

{'result': [{'atcocode': '9100DOVERP',
             'crscode': 'DVP',
             'distance': 881.148432224,
'latlong': {'coordinates': [1.3052936134036113, 51.12569875059288],
                         'crs': {'properties': {'name': 'EPSG4326'},
                                 'type': 'name'},
                         'type': 'Point'},
             'ospoint': {'coordinates': [631380.0, 141464.0],
                         'crs': {'properties': {'name': 'EPSG27700'},
                                 'type': 'name'},
                         'type': 'Point'},
             'stationname': 'Dover Priory Rail Station',
             'tiploccode': 'DOVERP'}],
 'success': True}

Use this in combination with Jon Ribbens' answer.


--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to