JSON confusion

Steve Simmons square.steve at gmail.com
Wed Aug 17 13:01:31 EDT 2016



On 17/08/2016 17:49, Jon Ribbens wrote:
> On 2016-08-17, Steve Simmons <square.steve at gmail.com> 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
> It's not clear what the problem is.
Yes, that was the problem!  I wasn't sure if I was being stupid (yes!) 
about the Python or the JSON.  Turns out, it was a bit of both ;-)
> Does this help:
>
>    print(p_json["result"][0]["stationname"])
>    print(p_json["result"][0]["latlong"]["coordinates"])
>
> ?
Yes, immensely.

> (To extract an item from a JSON object you index it with a string,
> e.g. ["foo"]; to extract an item from an array you use an integer,
> e.g. [0].)
Thanks very much, hopefully that'll set me on my way.

SteveS



More information about the Python-list mailing list