从GitHub仓库读取JSON文件时遭遇SSL证书错误的解决方案咨询
Hey, let's break down your problem and fix it step by step—you've got two key issues here:
1. You're using the wrong GitHub URL
The link https://github.com/UNAME/REPO/blob/master/test1.json points to GitHub's web page for displaying the file, not the raw JSON content. Even if you fixed the SSL error, you'd still get a JSON parsing failure because you're trying to load HTML as JSON.
To get the raw file, replace blob in the URL with raw:https://github.com/UNAME/REPO/raw/master/test1.json
2. SSL Certificate Verification Failure
This error happens because your local Python environment can't verify GitHub's SSL certificate. Here are two solutions, ordered by recommendation:
Option 1: Fix the SSL Certificates (Recommended, Secure)
This resolves the issue long-term without compromising security:
- macOS: Open your terminal and run the certificate installation command for your Python version. For example, if you're using Python 3.10:
/Applications/Python\ 3.10/Install\ Certificates.command - Windows/Linux: Update the
certifipackage (which provides trusted SSL certificates) and use it in your code:
First, run this in terminal:
Then modify your code to use the certifi certificate bundle:pip install --upgrade certifiimport json import certifi from urllib.request import urlopen # Use the raw GitHub URL here url = "https://github.com/UNAME/REPO/raw/master/test1.json" with urlopen(url, cafile=certifi.where()) as response: data = json.loads(response.read()) print(data)
Option 2: Temporarily Disable SSL Verification (Not Recommended, For Testing Only)
If you just need a quick test and understand the security risks (this makes your request vulnerable to man-in-the-middle attacks), you can create an SSL context that skips verification:
import json import ssl from urllib.request import urlopen url = "https://github.com/UNAME/REPO/raw/master/test1.json" # Create an SSL context that doesn't verify certificates ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE with urlopen(url, context=ctx) as response: data = json.loads(response.read()) print(data)
Final Notes
Always go with Option 1 for production code. Fixing the SSL certificates is the secure, sustainable solution, and using the raw GitHub URL ensures you're actually loading JSON data instead of HTML.
内容的提问来源于stack exchange,提问作者Andy Thomspon




