我正在try 将csv格式转换为JSON,我在谷歌上搜索到,我没有找到正确的方法来修改它以获得所需的格式.

这是我用python编写的代码:

import csv
import json

def csv_to_json(csvFilePath, jsonFilePath):
    jsonArray = []

    #reading csv (encoding is important)
    with open(csvFilePath, encoding='utf-8') as csvf:
        #csv library function
        csvReader = csv.DictReader(csvf)

        #convert each csv row into python dictionary
        for column in csvReader:
            #add this python dictionary to json array
            jsonArray.append(column)

    #convertion
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)

csvFilePath='example.csv'
jsonFilePath='output.json'
csv_to_json(csvFilePath, jsonFilePath)

这是我的csv文件格式:

enter image description here

我的实际JSON输出:

[
    {
        "Area": "IT",
        "Employee": "Carl",        
    },
    {
        "Area": "IT",
        "Employee": "Walter",      
    },
    {
        "Area": "Financial Resources",
        "Employee": "Jennifer",      
    }
]

我想要的JSON输出:

[
    {
        "Area": "IT",
        "Employee": ["Carl","Walter"],
    },
    {
      "Area": "Financial Resources",
      "Employee": ["Jennifer"],
    }
    
]

提前谢谢!

推荐答案

像这样的事情应该管用.

def csv_to_json(csvFilePath, jsonFilePath):
    areas = {}
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)
        for column in csvReader:
            area, employee = column["Area"], column["Employee"] # split values 
            if area in areas:  # add all keys and values to one dictionary
                areas[area].append(employee)
            else:
                areas[area] = [employee]
    # convert dictionary to desired output format.
    jsonArray = [{"Area": k, "Employee": v} for k,v in areas.items()]
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonString = json.dumps(jsonArray, indent=4)
        jsonf.write(jsonString)

Python相关问答推荐

单击Cookie横幅错误并在Selenium中启用搜索栏

修剪Python框架中的尾随NaN值

如何将 map 数组组合到pyspark中每列的单个 map 中

如何将自动创建的代码转换为类而不是字符串?

按日期和组增量计算总价值

单击Python中的复选框后抓取数据

Python如何让代码在一个程序中工作而不在其他程序中工作

将嵌套列表的字典转换为数据框中的行

Python -Polars库中的滚动索引?

在函数内部使用eval(),将函数的输入作为字符串的一部分

如何计算两极打印机中 * 所有列 * 的出现次数?

Pystata:从Python并行运行stata实例

按列分区,按另一列排序

无法通过python-jira访问jira工作日志(log)中的 comments

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

如何将多进程池声明为变量并将其导入到另一个Python文件

Odoo 16使用NTFS使字段只读

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

提取相关行的最快方法—pandas

如何在Pyplot表中舍入值