You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python导入GitHub公共JSON数据报错求助:JSONDecodeError与文件找不到问题

问题分析与解决方案

第一种方式报错原因

你用的是GitHub文件的网页展示URL(带blob的地址),这个URL返回的是GitHub的HTML页面,不是纯JSON数据,所以json.loads()解析时会因为内容不符合JSON格式报错。

第二种方式报错原因

open()函数仅支持读取本地文件路径,不能直接传入远程URL,它会把URL当作本地目录/文件名查找,自然找不到对应文件。


修正后的代码示例

第一种方式(修正URL为原始JSON地址)

获取GitHub上JSON文件的原始内容URL:在GitHub文件页面点击右上角的「Raw」按钮,复制对应的纯JSON地址替换原URL即可:

import json
import urllib.request
# 替换为原始JSON内容的URL
with urllib.request.urlopen("https://raw.githubusercontent.com/Ovi/DummyJSON/master/src/data/carts.json") as url:
    pydc = json.loads(url.read().decode())
    print(pydc)

第二种方式(改为远程请求读取,或下载后读本地文件)

方式一:用urllib.request远程读取

同样需要使用原始JSON地址:

import json
import urllib.request
with urllib.request.urlopen("https://raw.githubusercontent.com/PhonePe/pulse/master/data/aggregated/transaction/country/india/2018/1.json") as url:
    data = json.loads(url.read().decode())
    print(data)

方式二:先下载文件到本地,再用open()读取

如果想使用open(),先把JSON文件下载到本地,然后传入本地文件路径:

import json
# 假设文件已下载到本地当前目录,文件名为1.json
with open("1.json", "r", encoding="utf-8") as file:
    data = json.load(file)
    print(data)

内容的提问来源于stack exchange,提问作者Ezhil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 03:42:50