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

遍历JSON列表解析元素至CSV时遇TypeError问题求助

问题与解决方案

问题描述

通过以下代码爬取电商网站接口,得到一个JSON响应列表responses:

responses.append(requests.request("POST", url, data=payload, headers=headers).json())

每个JSON响应中包含若干车辆信息元素,需要提取指定字段存入CSV,但现有代码触发如下错误:

TypeError: list indices must be integers or slices, not dict
此前还出现过索引越界错误。

用户原始代码:

data = []
for j in responses : #iterating through the list of jsons
    for i in range(len(responses[j]['data']['search']['announcements']['data'])) : #iterating through the elements
        data.append([responses[j]["data"]["search"]["announcements"]['data'][i]['id'],
                     responses[j]["data"]["search"]["announcements"]['data'][i]['title'],
                     responses[j]["data"]["search"]["announcements"]['data'][i]['createdAt'],
                     responses[j]["data"]["search"]["announcements"]['data'][i]['description'],
                     responses[j]["data"]["search"]["announcements"]['data'][i]['cities'][0]['name'],
                     responses[j]["data"]["search"]["announcements"]['data'][i]['cities'][0]['region']['name'],
                     responses[j]["data"]["search"]["announcements"]['data'][i]['price']
                     
                 ])
        print(j)
Cars_data = pd.DataFrame(data,columns=['id','Car_name','Post_Created','description','city_name','wilaya','price'])

单个车辆信息JSON格式示例(简化版):

{
    "id": "34456405",
    "title": "Hyundai i10 2012 GLS",
    "createdAt": "2022-12-07T11:33:06.000Z",
    "description": "سيارة نقية و مغلفة، فيها شوية صبيغة على برا كيما في الصور، محرك ما شاء الله \n 10/10 ما يسخن ما ينقص زيت. 00 مصروف ",
    "cities": [
        {
            "name": "Alger centre",
            "region": {
                "name": "Algiers"
            }
        }
    ],
    "price": 1450000
}

错误原因分析

  1. TypeError原因:for j in responses循环中,j是列表中的单个JSON响应对象(dict类型),而非列表索引,此时用responses[j]去访问列表元素,自然会触发"列表索引必须是整数/切片,不能是dict"的错误。
  2. 索引越界原因:代码中直接使用cities[0],如果某条车辆信息的cities字段是空数组,就会触发索引越界错误。

修正后的代码

import pandas as pd

data = []
# 遍历每个JSON响应对象
for resp in responses:
    # 提取当前响应中的车辆数据列表
    car_items = resp['data']['search']['announcements']['data']
    # 遍历每一条车辆信息
    for item in car_items:
        # 处理cities为空的情况,避免索引越界
        city_name = item['cities'][0]['name'] if item['cities'] else None
        wilaya = item['cities'][0]['region']['name'] if (item['cities'] and item['cities'][0].get('region')) else None
        
        # 提取字段存入临时列表
        data.append([
            item['id'],
            item['title'],
            item['createdAt'],
            item['description'],
            city_name,
            wilaya,
            item['price']
        ])

# 转为DataFrame并保存为CSV文件
Cars_data = pd.DataFrame(data, columns=['id','Car_name','Post_Created','description','city_name','wilaya','price'])
# 保存时指定utf-8-sig编码,避免中文乱码
Cars_data.to_csv('vehicles_data.csv', index=False, encoding='utf-8-sig')

代码改进说明

  • 直接遍历responses中的响应对象resp,不再通过索引访问,解决TypeError问题
  • 直接遍历车辆数据列表的元素item,无需使用range(len(...))和索引i,代码更简洁易读
  • 对cities及region字段做判空处理,避免索引越界错误
  • 添加CSV保存代码,指定utf-8-sig编码防止中文乱码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:55:13