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

如何用Python将CSV中的名称转换为JS Array格式的JSON

问题解析与修正方案

嘿,刚上手Python就能尝试CSV转JSON的任务,已经超棒啦!你遇到的核心问题是用了字典存储企业名称,而字典在JSON里会被序列化成键值对的对象结构,而你需要的是数组(对应Python里的列表)。

关键错误点

你原来的代码里初始化了data = {}(字典),然后用data[company] = line[2]把企业名同时作为键和值存入,这就导致最终JSON里names是一个对象而非数组。

修正后的完整代码

import csv, json
csvPath = "forbes_pub_top_2000.csv"
jsonPath = "pub.json"

# 把data改成列表,用来存储企业名称
data = []
with open(csvPath, 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)  # 跳过表头行
    for line in csv_reader:
        company = line[2]
        data.append(company)  # 将企业名添加到列表中

# 构建根结构,names对应这个列表
root = {}
root["names"] = data

# 写入JSON文件
with open(jsonPath, 'w') as json_file:
    json_file.write(json.dumps(root, indent=4))

修正说明

  1. 将data从字典{}改为列表[],列表在JSON中会被序列化为数组[]
  2. 把data[company] = line[2]替换为data.append(company),这样是把每个企业名追加到列表末尾,而不是添加键值对

输出效果

运行修正后的代码,你就能得到期望的JSON结构:

{
    "names": ["ICBC", "China Construction Bank", "Berkshire Hathaway", "JPMorgan Chase", "Wells Fargo", "Agricultural Bank of China", "Bank of America", "Bank of China", ... ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:21:05