如何用Python将CSV转换为指定嵌套结构的JSON?
CSV转嵌套结构JSON的实现方案
问题背景
我的CSV文件内容如下:
"id","first name","lastname","zipcode","city" "10001","test","sample","3333","LA"
我已使用以下Python代码将CSV转换为JSON:
import csv import json def csv_to_json(csvFilePath, jsonFilePath): jsonArray = [] with open('Sample.csv', encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for row in csvReader: jsonArray.append(row) with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonString = json.dumps(jsonArray, indent=4) jsonf.write(jsonString) csvFilePath = r'data.csv' jsonFilePath = r'data.json' csv_to_json(csvFilePath, jsonFilePath)
转换后的JSON数据格式如下:
[ { "id": "10001", "firstname": "test", "lastname": "sample", "zipcode":"3333", "city": "LA" } ]
我希望将其转换为如下嵌套结构的JSON:
{ "id":"10001", "fullname":{ "firstname":"test", "lastname":"sample" }, "Address":{ "zipcode":"3333", "city":"LA" } }
实现方案
只需在遍历CSV行数据时,手动构造符合嵌套结构的字典,替换原代码中直接添加行数据的逻辑即可。同时修复原代码里未使用传入文件路径参数的问题,避免文件读取错误。
修改后的代码如下:
import csv import json def csv_to_json(csvFilePath, jsonFilePath): jsonArray = [] with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for row in csvReader: # 构造嵌套结构的目标字典 nested_row = { "id": row["id"], "fullname": { "firstname": row["first name"], "lastname": row["lastname"] }, "Address": { "zipcode": row["zipcode"], "city": row["city"] } } jsonArray.append(nested_row) with open(jsonFilePath, 'w', encoding='utf-8') as jsonf: jsonString = json.dumps(jsonArray, indent=4) jsonf.write(jsonString) csvFilePath = r'data.csv' jsonFilePath = r'data.json' csv_to_json(csvFilePath, jsonFilePath)
关键说明
- 针对CSV表头的
"first name",如果需要嵌套后的键为"firstname"(与期望的JSON结构一致),直接在构造fullname字典时指定对应键名即可。 - 修复了原代码中函数参数
csvFilePath未被使用的问题,确保读取的是传入的目标CSV文件。 - 转换后的JSON会是包含嵌套结构对象的数组(适配CSV多行数据场景),若CSV仅一行,最终JSON数组内只会有一个符合要求的嵌套对象。
内容的提问来源于stack exchange,提问作者alearn_92
相关产品推荐
相关产品推荐

