python - CSV 到 JSON 转换器(按相同键值分组)

标签 python json pandas csv request

我正在尝试将 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 - CSV 到 JSON 转换器(按相同键值分组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73042986/

相关文章:

python - 基于原型(prototype)委托(delegate)的模型如何在 Python 中工作?

javascript - 如何调用 he.js 函数来解码 JSON 输出元素

python - Pandas:将数据帧填充到最大行长度

python - Pandas 分发时间序列数据

jquery - 使用 jQuery 组织 JSON 结果

python - 为什么 f-strings 格式不适用于 Pandas DataFrames?

python - 如何使用 Poetry 创建可部署的 Python Lambda zip

python - 在 Python 中解决奇异值分解 (SVD)

python - 如何解决 rq 多任务 h12 heroku 超时?

java - jackson 映射关系