Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning the minimum value in a JSON array

Tags:

python

json

Good evening folks! I have been wracking my brain on this one for a good few hours now and could do with a little bit of a pointer in the right direction. I'm playing around with some API calls and trying to make a little project for myself.

The JSON data is stored in Arrays, and as such to get the information I want (it is from a Transport API) I have been making the following

x = apirequest
x = x.json


for i in range(0,4):
    print(x['routes'][i]['duration'])
    print(x['routes'][i]['departure_time'])  
    print(x['routes'][i]['arrival_time'])

This will return the following

06:58:00
23:39
06:37
05:08:00
05:14
10:22
03:41:00
05:30
09:11
03:47:00
06:24
10:11

What I am trying to do, is return only the shortest journeys - I could do it if it was a single layer JSON string but I am not too familliar with multi-level arrays. I can't return ['duration'] without utilising ['routes'] and route indicator (in this case 0 through 3 or 4).

I can use an if statement to iterate through them easily enough, but there must be a way to accomplish it directly through the JSON that I am missing. I also thought about adding the results to a separate array and then filtering that - but there is a few other fields I want to grab from the data when I've cracked this part.

What I am finding as I learn is that I tend to do things a long winded way, often finding out my 10-15 line solutions on codewars are actually aimed at being done in 2-3 lines.

Example JSON data

{
    "request_time": "2018-05-29T19:03:04+01:00",
    "source": "Traveline southeast journey planning API",
    "acknowledgements": "Traveline southeast",
    "routes": [{
        "duration": "06:58:00",
        "route_parts": [{
            "mode": "foot",
            "from_point_name": "Corunna Court, Wrexham",
            "to_point_name": "Wrexham General Rail Station",
            "destination": "",
            "line_name": "",
            "duration": "00:36:00",
            "departure_time": "23:39",
            "arrival_time": "00:15"
        }]
    }]
}

Hope you can help steer me in the right direction!


1 Answers

Here's one solution using datetime.timedelta. Data from @fferri.

from datetime import timedelta

x = {'routes': [{'duration':'06:58:00','departure_time':'23:39','arrival_time':'06:37'},
                {'duration':'05:08:00','departure_time':'05:14','arrival_time':'10:22'},
                {'duration':'03:41:00','departure_time':'05:30','arrival_time':'09:11'},
                {'duration':'03:47:00','departure_time':'06:24','arrival_time':'10:11'}]}

def minimum_time(k):
    h, m, s = map(int, x['routes'][k]['duration'].split(':'))
    return timedelta(hours=h, minutes=m, seconds=s)

res = min(range(4), key=minimum_time)  # 2

You can then access the appropriate sub-dictionary via x['routes'][res].

like image 101
jpp Avatar answered Jul 19 '26 07:07

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!