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

如何将CSV按预期格式转换为JSON?Python代码问题解决

CSV转JSON格式问题解决办法

问题核心:你的CSV文件用**分号(;)**作为分隔符,但Python的csv.DictReader默认使用逗号(,)作为分隔符,导致整行内容被识别为单个键值对。

修正后的基础代码

import csv

filename = "forcebrute.csv"

# 指定分隔符为分号
with open(filename, 'r') as data:
    for line in csv.DictReader(data, delimiter=';'):
        print(line)

运行结果

执行后会输出每个字段独立的键值对:

{'name': 'Action-1', 'price': '20', 'profit': '5'}
{'name': 'Action-2', 'price': '30', 'profit': '10'}
{'name': 'Action-3', 'price': '50', 'profit': '15'}
{'name': 'Action-4', 'price': '70', 'profit': '20'}
{'name': 'Action-5', 'price': '60', 'profit': '17'}

输出标准JSON格式(可选)

如果需要生成规范的JSON结构,可结合json模块,同时将数字字段转为数值类型:

import csv
import json

filename = "forcebrute.csv"
result = []

with open(filename, 'r') as data:
    reader = csv.DictReader(data, delimiter=';')
    for row in reader:
        # 将price和profit转为整数
        row['price'] = int(row['price'])
        row['profit'] = int(row['profit'])
        result.append(row)

# 格式化输出JSON
print(json.dumps(result, indent=2))

对应的JSON输出:

[
  {
    "name": "Action-1",
    "price": 20,
    "profit": 5
  },
  {
    "name": "Action-2",
    "price": 30,
    "profit": 10
  },
  {
    "name": "Action-3",
    "price": 50,
    "profit": 15
  },
  {
    "name": "Action-4",
    "price": 70,
    "profit": 20
  },
  {
    "name": "Action-5",
    "price": 60,
    "profit": 17
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:00:23