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

从GET请求返回的Zip文件提取JSON至路径或Pandas DataFrame

问题需求

通过GET请求访问目标URL后,接口返回.zip、.zipsig和.txt文件,我仅关注包含数十个.json文件的.zip包,需要实现以下需求(优先实现第一项):

  • 直接将所有.json文件的数据合并导入至单个Pandas DataFrame
  • 或将所有.json文件提取至指定文件夹

现有代码仅能提取.zip包内的第一个文件,需修改以满足需求:

license = requests.get(url, headers={'Authorization': "Api-Token " + 'blah'})
z = zipfile.ZipFile(io.BytesIO(license.content))
billingRecord = z.namelist()[0]
z.extract(billingRecord, path = "C:\Users\Me\Downloads\Json license")

方案1:提取所有JSON文件到指定文件夹

遍历.zip包内的所有文件,筛选出.json后缀的文件并逐个提取:

import requests
import zipfile
import io

url = "你的目标URL"
token = "blah"
target_path = r"C:\Users\Me\Downloads\Json license"

# 发起请求获取压缩包
response = requests.get(url, headers={'Authorization': f"Api-Token {token}"})
z = zipfile.ZipFile(io.BytesIO(response.content))

# 筛选并提取所有JSON文件
for file_name in z.namelist():
    # 跳过文件夹,只处理.json文件
    if file_name.endswith('.json') and not file_name.endswith('/'):
        z.extract(file_name, path=target_path)

方案2:直接合并JSON数据到Pandas DataFrame

无需提取本地文件,直接读取压缩包内的JSON内容并合并为单个DataFrame:

import requests
import zipfile
import io
import pandas as pd
import json

url = "你的目标URL"
token = "blah"

response = requests.get(url, headers={'Authorization': f"Api-Token {token}"})
z = zipfile.ZipFile(io.BytesIO(response.content))

all_json_data = []

for file_name in z.namelist():
    if file_name.endswith('.json') and not file_name.endswith('/'):
        # 读取压缩包内的JSON文件
        with z.open(file_name) as json_file:
            data = json.load(json_file)
            # 兼容单条记录和列表格式的JSON
            if isinstance(data, list):
                all_json_data.extend(data)
            else:
                all_json_data.append(data)

# 合并为DataFrame
combined_df = pd.DataFrame(all_json_data)
# 可选:将DataFrame保存到本地
combined_df.to_csv(r"C:\Users\Me\Downloads\combined_license_data.csv", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:00:58