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

如何读取Python中未被识别为列表的类列表字符串数据?

问题分析与解决方案

你的问题根本不是单引号导致的——response.json()已经把API返回的JSON转换成了原生Python数据结构(列表、字典),ColData本身就是列表,不是字符串。是代码逻辑有误,才导致你误以为拿到的是类列表字符串。

代码中的问题点

  1. 循环里没必要用x索引,for row in row_data已经能拿到每一行数据,重复调用row_data[x]完全多余。
  2. col_data = [rowx_data.get('ColData')]这一步把ColData列表额外包了一层新列表,再取col_data[0]属于多此一举,直接获取ColData即可。
  3. 最后一行是汇总行(带Summary键),没有ColData字段,需要跳过否则会报错。

修正后的完整代码

import csv
import requests

# 替换为你的API请求逻辑
response = requests.get("你的API接口地址")
data = response.json()
rows = [('Account', 'Debit', 'Credit')]
row_data = data['Rows']['Row']

for row in row_data:
    # 跳过汇总行
    if 'Summary' in row:
        continue
    col_data = row.get('ColData')
    if not col_data:
        continue
    # 直接从原生列表中提取value值
    account = col_data[0]['value']
    debit = col_data[1]['value']
    credit = col_data[2]['value']
    rows.append((account, debit, credit))

# 写入CSV文件
with open('trial_balance.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(rows)

说明

  • 遍历行数据时,先判断是否为汇总行,避免无意义的处理。
  • row.get('ColData')直接拿到原生Python列表,可直接通过索引+键名提取value。
  • 最后用Python内置的csv模块将数据写入文件,生成符合需求的CSV。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 20:07:00