Google Directions API, Part 3

Contents

Indices and tables

Exercise

For this week, the goal is to implement a function that does the following:

  • It should accept one parameter, the raw json file returned from your http request.

  • It should return the parsed json file as a python dictionary.

  • It should print some basic information from the file.

    • For example, the number of legs in the trip and the trip details for each leg.
  • After getting the initial parsing working, try to implement the –load and –output switches

    • Load should accept a path to a json file, and parse the contents instead of querying the api.
    • Output should save the raw json to a file for future use.

This will require using the json package, especially json.load() and/or json.loads() Note: There is a json parser built into requests. However we decided to use the json library directly so you can practice what you’ve learned.

On completing of this exercise, you should be able to run your stub program and have it do the following:

  • Parse the arguments as outlined the previous weeks.
  • Print the number of legs in the trip and the start/end/distance/duration of each leg.
  • Print the keys contained in the parsed json dictionary
  • Pass the –output argument and save a json file
  • Pass the –load argument and load a previously saved json file

Hints

To help you get started, here is one possible signature for the json parsing function:

def parse_json(contents):
    """
    Demonstration of parsing the input json file and printing some information from it.
    :param contents: The JSON file to be parsed. Either bytes or a string.
    :return: The parsed JSON as a nested dictionary.
    """
  • Take a look at the json results from the query and/or the API site to get a feel for what the keys at each level are. You can use the PyCharm debugger to examine the dictionary returned from the JSON parser for example.

Solution

When you are ready to see one possible solution, try this file