CSV文件看起来是这样的,我有id和标记。但是有些标记可能有多个值,每个值都有一个列,所以有些标记可能有多个列。
id,tags
403744,[""]
403745,["phsecurity"]
403750,["unit-testing","testing","boolean"]
403757,[""]
403759,["object-oriented","architectural-patterns"]我尝试使用这个python代码来转换:
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中,知道如何修复它吗?谢谢
发布于 2022-06-27 21:30:27
最好的方法是改变输入文件的生成方式。但是如果不可能,这个脚本将尝试解析它并保存Json文件:
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
{
"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"
]
}
}https://stackoverflow.com/questions/72778207
复制相似问题