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

Python脚本导出JSON仅输出y、meas、label无数据的修复方案咨询

Python拉取接口数据导出Excel无有效数据排查修复方案

排查步骤

  • 第一步:验证接口返回合法性
    先在resp = requests.get(url=r)后添加两行打印代码,确认接口返回正常:
    print(resp.status_code) # 确认返回状态为200,排除4xx/5xx请求错误
    print(resp.json()) # 确认返回的JSON结构符合预期,没有为空
    
    同时打印len(df['dataset'])确认item_list不为空,如果该值为0,说明接口返回的dataset字段没有数据,循环逻辑不会执行,自然只有列名无内容。
  • 第二步:排查异常捕获掩盖的字段匹配问题
    现有代码用了无差别try-except吞掉了所有赋值异常,哪怕字段层级不匹配、数组越界也只会静默赋值为np.nan。可以暂时注释掉所有try-except,运行代码看是否抛出KeyError/IndexError,就能定位是data字段不存在、data数组为空,还是meas/label字段名和实际返回不匹配(比如大小写差异、拼写差异)。
  • 第三步:修复循环内索引覆盖问题
    现有代码循环内永远对loc[0]赋值,哪怕item_list有多个元素,也只会保留最后一个元素的赋值结果,且如果item_list为空,current_df不会有任何行数据,最终导出只有列名。

修复后参考代码

import requests
import pandas as pd
import numpy as np

total_df = pd.DataFrame()
request_list = ["LInk",]

for r in request_list:
    resp = requests.get(url=r)
    # 新增请求状态校验
    if resp.status_code != 200:
        print(f"请求{r}失败,状态码:{resp.status_code}")
        continue
    resp_data = resp.json()
    df = pd.json_normalize(resp_data)
    # 校验dataset字段存在且非空
    if 'dataset' not in df.columns or len(df['dataset']) == 0:
        print(f"接口{r}返回无有效dataset数据")
        continue
    item_list = df['dataset']
    current_rows = []
    for i in item_list:
        row = {}
        # 可根据实际排查到的字段层级修改取值逻辑
        try:
            row['y'] = i['data'][0]['y']
        except:
            row['y'] = np.nan
        try:
            row['meas'] = i['meas']
        except:
            row['meas'] = np.nan
        try:
            row['label'] = i['label']
        except:
            row['label'] = np.nan
        current_rows.append(row)
    current_df = pd.DataFrame(current_rows)
    total_df = pd.concat([total_df,current_df], ignore_index=True)

total_df.to_excel('C:/Users/svetl/Onedrive/Desktop/work/output.xlsx',index=False)  

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:00:00