Assign JSON to variable in python


#1

Hi, hope this is not a silly question…

import openrouteservice
import json
import requests

coords = ((-89.587858,36.876719),(-97.078065, 32.934292))

client = openrouteservice.Client(key='myapi_key')
routes = client.directions(coords)

In python i can see that the routes is now a ‘dict’ object.

print(type(routes))
<class ‘dict’>

How can I assign the “distance” information retrieved by the api?

I’ve tried a few things with no avail:

print(routes[0]['summary'])
distance = loc['routes']['summary']

Thanks!


#3

Just a little silly;)

Inspect your dict! It’s all right there. First print the keys of routes (print(routes.keys()), then go further from there, e.g. print(routes['routes'] etc.

Sorry that I don’t give you the exact answer, but I find it’s better to help people to help themselves.

I deleted your JSON post, it doesn’t add any benefit…


#4

Thanks nils! You shed some light on the problem!


#5

I had to use a helper function to do this:

# recursivejson.py

def extract_values(obj, key):
    """Pull all values of specified key from nested JSON."""
    arr = []

    def extract(obj, arr, key):
        """Recursively search for values of key in JSON tree."""
        if isinstance(obj, dict):
            for k, v in obj.items():
                if isinstance(v, (dict, list)):
                    extract(v, arr, key)
                elif k == key:
                    arr.append(v)
        elif isinstance(obj, list):
            for item in obj:
                extract(item, arr, key)
        return arr

    results = extract(obj, arr, key)
    return results

then,

distances = extract_values(rt, dist)
haul_distance = distances[0]/1000

:slight_smile: