如何在Jupyter中从URL提取JSON数据?含指定站点提取需求
Hey there! Pulling JSON data from that Ford GoBike GBFS URL in Jupyter is super doable with a few standard Python tools. Let me walk you through exactly how to do it, including handling the response and digging into the data.
Step 1: Install Required Libraries (If You Haven’t Already)
First, make sure you have requests (for fetching the data) and optionally pandas (for easier data manipulation) installed. In Jupyter, you can run this magic command directly in a cell:
!pip install requests pandas
Step 2: Import the Libraries
Next, import the tools we need in a new cell:
import requests import json import pandas as pd # Optional, but great for tabular data
Step 3: Fetch the JSON Data from the URL
Let's target the specific URL you mentioned: https://gbfs.fordgobike.com/gbfs/gbfs.json. We'll send a GET request, check if it succeeded, then parse the JSON.
Here’s the code with basic error handling (so you don’t get stuck if the request fails):
# Define the target URL url = "https://gbfs.fordgobike.com/gbfs/gbfs.json" try: # Send the GET request response = requests.get(url) # Raise an error if the request wasn't successful (e.g., 404, 500) response.raise_for_status() # Parse the JSON data gbfs_data = response.json() print("Successfully fetched and parsed the JSON data!") except requests.exceptions.RequestException as e: print(f"Oops, something went wrong with the request: {e}")
Step 4: Explore and Extract Data
Now that you have the parsed JSON, you can start exploring it. Let's first take a look at the top-level keys to understand the structure:
print("Top-level keys in the JSON data:", list(gbfs_data.keys()))
For example, the data key contains the actual feeds. Let's extract that and turn it into a pandas DataFrame for easier viewing:
# Extract the feeds from the data section feeds = gbfs_data["data"]["en"]["feeds"] # Convert to a DataFrame feeds_df = pd.DataFrame(feeds) display(feeds_df)
If you want to dig deeper into a specific feed (like station status), you could use the url from the feeds DataFrame to fetch that next layer of data—just repeat the same request/parse process for that URL.
Quick Tips
- Always use
raise_for_status()to catch HTTP errors early (like broken links or server issues). - If the JSON is large, use
json.dumps(gbfs_data, indent=4)to print it in a formatted, readable way. - Pandas is optional but makes it way easier to filter, sort, and analyze structured JSON data.
内容的提问来源于stack exchange,提问作者Rick J

