如何将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
相关产品推荐
相关产品推荐

