首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将此格式的csv文件转换为json文件?

如何将此格式的csv文件转换为json文件?
EN

Stack Overflow用户
提问于 2022-06-27 20:55:21
回答 1查看 51关注 0票数 1

CSV文件看起来是这样的,我有id和标记。但是有些标记可能有多个值,每个值都有一个列,所以有些标记可能有多个列。

代码语言:javascript
复制
id,tags
403744,[""]
403745,["phsecurity"]
403750,["unit-testing","testing","boolean"]
403757,[""]
403759,["object-oriented","architectural-patterns"]

我尝试使用这个python代码来转换:

代码语言:javascript
复制
import csv
import json


# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):

    # create a dictionary
    data = {}

    # Open a csv reader called DictReader
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)

        # Convert each row into a dictionary
        # and add it to data
        for rows in csvReader:

            # Assuming a column named 'No' to
            # be the primary key
            key = rows['id']
            data[key] = rows

    # Open a json writer, and use the json.dumps()
    # function to dump data
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonf.write(json.dumps(data, indent=4))

# Driver Code


# Decide the two file paths according to your
# computer system
csvFilePath = r'aaa.CSV'
jsonFilePath = r'bbb.json'

# Call the make_json function
make_json(csvFilePath, jsonFilePath)

但是,它给出了如下格式:{ "403744":{ "id":{ "id":"403744",“标记”:“}”},"403745":{ "id":"403745",“标记”:“phsecurity”},"403750":{“id”:"403750",“标签”:“[”单元-测试“”,"null":“测试”,“布尔”]}}

这不是我想在标记中添加"testing“和”format.Like“的正确的json。您还可以看到,它将"“或”“放入值too.Anyone中,知道如何修复它吗?谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-27 21:30:27

最好的方法是改变输入文件的生成方式。但是如果不可能,这个脚本将尝试解析它并保存Json文件:

代码语言:javascript
复制
import json
from ast import literal_eval

data = []
with open("input.csv", "r") as f_in:
    for line in map(str.strip, f_in):
        if line == "":
            continue
        line = list(map(str.strip, line.split(",", maxsplit=1)))
        data.append(line)

# skip header:
data = data[1:]


data = {key: {"id": key, "tags": literal_eval(tags)} for key, tags in data}
print(data)

with open("output.json", "w") as f_out:
    json.dump(data, f_out, indent=4)

将创建output.json

代码语言:javascript
复制
{
    "403744": {
        "id": "403744",
        "tags": [
            ""
        ]
    },
    "403745": {
        "id": "403745",
        "tags": [
            "phsecurity"
        ]
    },
    "403750": {
        "id": "403750",
        "tags": [
            "unit-testing",
            "testing",
            "boolean"
        ]
    },
    "403757": {
        "id": "403757",
        "tags": [
            ""
        ]
    },
    "403759": {
        "id": "403759",
        "tags": [
            "object-oriented",
            "architectural-patterns"
        ]
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72778207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档