You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Maps API获取导航路线时嵌套steps解析错误求助

Fixing Nested Steps Parsing in Google Maps Directions API with Python

Hey there, let's work through those two parsing issues you're hitting with the Google Maps Directions API—they're common pitfalls with nested API responses, and we can fix them easily!

1. Fixing the KeyError: 'steps'

The first problem is straightforward: not every step object has a nested steps field. For example, simple walk or train steps might not have sub-instructions, so when you try to loop over step['steps'] directly, Python throws an error when that key doesn't exist.

To fix this, use the dict.get() method—it returns a default value (like an empty list) if the key isn't present, so your loop won't break:

# Instead of directly accessing step['steps']
nested_steps = step.get('steps', [])

2. Fixing the list index must be int not str Error

The second issue happens because step['steps'] is a list of step objects, not a dictionary. You can't access step['steps']['steps'] directly—you need to iterate over each item in the list first. Plus, those sub-steps might have their own nested steps fields, so a recursive approach is perfect to extract all instructions no matter how deep they go.

Updated Code with Recursive Parsing

Here's your revised code that handles both issues and pulls every navigation instruction, including deeply nested ones:

import googlemaps
from datetime import datetime

gmaps = googlemaps.Client(key='HIDDEN')
now = datetime.now()
directions_result = gmaps.directions(
    "Sydney Olympic Park, New South Wales 2127, Australia",
    "Parramatta, NSW",
    mode="transit",
    departure_time=now
)

def extract_all_instructions(step):
    """Recursively pull all instructions from a step and its nested sub-steps"""
    # Print the current step's details
    current_instruction = f"{step['html_instructions']} {step['distance']['text']} {step['duration']['text']}"
    print(current_instruction)
    
    # Safely check for nested steps and process each one
    nested_steps = step.get('steps', [])
    for sub_step in nested_steps:
        extract_all_instructions(sub_step)

# Process each leg in the directions response
for leg in directions_result[0]['legs']:
    startAddress = leg['start_address']
    print("Start Address:", startAddress)
    endAddress = leg['end_address']
    print("End Address:", endAddress)
    distance = leg['distance']['text']
    print("Distance:", distance)
    duration = leg['duration']['text']
    print("Duration:", duration)
    
    # Process every top-level step in the leg
    for step in leg['steps']:
        extract_all_instructions(step)

What Changed?

  • Recursive function: The extract_all_instructions() function handles both top-level steps and any nested sub-steps. It first prints the current step's instruction, then checks for nested steps (using get() to avoid errors) and recursively processes each one.
  • Safe key access: No more direct step['steps'] calls—we use step.get('steps', []) to default to an empty list if the key is missing.
  • No hardcoded indexes: We removed the step['steps'][0] line that caused the index error, and instead iterate over every sub-step in the nested list.

This code will now output all navigation instructions, no matter how deeply nested they are in the API response.

内容的提问来源于stack exchange,提问作者Artemio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:23:48