Home >Backend Development >Python Tutorial >How to Make HTTP Requests and Parse JSON Data with Python?
Making HTTP Requests and Parsing JSON in Python
Python provides several powerful libraries for making HTTP requests and parsing JSON. One recommended option is the requests library. Here's how to use it to dynamically query Google Maps and parse the JSON response:
import requests url = 'http://maps.googleapis.com/maps/api/directions/json' params = dict( origin='Chicago,IL', destination='Los+Angeles,CA', waypoints='Joplin,MO|Oklahoma+City,OK', sensor='false' ) resp = requests.get(url=url, params=params) data = resp.json() # Check the JSON Response Content documentation below
JSON Response Content:
The data variable now contains the parsed JSON response. You can access specific fields within the JSON using the dot operator:
print(data['routes'][0]['legs'][0]['distance']['text'])
This would print the distance of the first leg of the first route in plain text. Refer to the Google Maps Directions API documentation for more information on the JSON structure.
The above is the detailed content of How to Make HTTP Requests and Parse JSON Data with Python?. For more information, please follow other related articles on the PHP Chinese website!