Home >Backend Development >Python Tutorial >How to Make HTTP Requests and Parse JSON Data with Python?

How to Make HTTP Requests and Parse JSON Data with Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 10:16:03867browse

How to Make HTTP Requests and Parse JSON Data with Python?

HTTP Requests and JSON Parsing in 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn