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

Python 3从Google API JSON提取坐标时遇AttributeError问题求助

Fixing AttributeError: 'list' object has no attribute 'read' in Google Maps Geocoding Code

Hey there! Let's break down what's causing that error and get your coordinate extraction working smoothly for visualization.

What's Going Wrong?

The core issue comes from a misunderstanding of what the Google Maps geocoding library returns:

  • The gmaps.geocode() method automatically parses the API's JSON response into native Python objects (a list of dictionaries, as you saw in your printed output).
  • You tried using json.load(geocode_result.read()), but json.load() is meant for reading file-like objects—not Python lists. Since a list doesn't have a read() method, that's exactly why you're hitting the AttributeError.
  • On top of that, your original code was targeting address_components, but you actually need to access the geometry.location field to get the latitude and longitude values.

Corrected Code

Here's the fixed version that properly extracts the coordinates you need:

import googlemaps
import pprint
import simplejson as json
from datetime import datetime

gmaps = googlemaps.Client(key='insert a google API key')

# Geocode the address (returns a list of Python dictionaries)
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
pprint.pprint(geocode_result)

# Extract coordinates from the first (most accurate) result
first_result = geocode_result[0]
location_coords = first_result['geometry']['location']

# Convert to formatted JSON for your visualization workflow
geo_input = json.dumps(location_coords, indent=3)
pprint.pprint(geo_input)

Handling Multiple Geocoding Results

If your address might return multiple matches (like a vague street name), you can loop through all results to collect every set of coordinates:

# Collect coordinates from all geocoding results
all_location_coords = [
    result['geometry']['location'] 
    for result in geocode_result
]

# Convert to formatted JSON
geo_input = json.dumps(all_location_coords, indent=3)
pprint.pprint(geo_input)

Key Takeaways

  • Skip the json.load() call entirely—the googlemaps library handles JSON parsing for you out of the box.
  • Directly target geometry.location in the returned Python dictionary to grab your lat and lng values.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:51:52