Looping on a list in json
Cameron Simpson
cs at cskk.id.au
Sat Nov 4 17:27:00 EDT 2017
On 04Nov2017 14:01, Sayth Renshaw <flebber.crue at gmail.com> wrote:
>I want to get a result from a largish json api. One section of the json
>structure returns lists of data. I am wanting to get each resulting list
>returned.
>
>This is my code.
>import json
>from pprint import pprint
>
>with open(r'/home/sayth/Projects/results/Canterbury_2017-01-20.json', 'rb') as f, open('socks3.json','w') as outfile:
> to_read = json.load(f)
[...]
> meeting_id = to_read["RaceDay"]["Meetings"][0]
> result = meeting_id["Races"]
> #failing
> for item in result:
> pprint(["RacingFormGuide"]["Event"]["Runners"])
I'd just keep the interesting runners, along with their race numbers, in a
dict. The enumerate function is handy here. Something like (untested):
runner_lists = {}
for n, item in enumerate(result):
if this one is interested/not-filtered:
runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
and just return runner_lists. That way you know what the race numbers were for
each list of runners.
>What is the best way to and return the data?
The basic idea is to make a small data structure of your own (just the
dictionary runner_lists in the example above) and fill it in with the
infomation you care about in a convenient and useful shape. Then just return
the data structure.
The actual data structure will depend on what you need to do with this later.
Cheers,
Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)
More information about the Python-list
mailing list