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()), butjson.load()is meant for reading file-like objects—not Python lists. Since a list doesn't have aread()method, that's exactly why you're hitting theAttributeError. - On top of that, your original code was targeting
address_components, but you actually need to access thegeometry.locationfield 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—thegooglemapslibrary handles JSON parsing for you out of the box. - Directly target
geometry.locationin the returned Python dictionary to grab yourlatandlngvalues.
内容的提问来源于stack exchange,提问作者student
相关产品推荐
相关产品推荐

