我正在尝试使用python构建一个JSON文件,并从CSV文件开始。
CSV文件如下所示:
a,b,tableau.c,tableau2.d,tableau2.e,tableau2.f,tableau2.g,tableau.h
11725,11741,false,N/A,true,23,N/A,false
到目前为止,我正在设法将csv文件转换为JSON文件,并将其排列如下:
[
{
"a": "11725",
"b": "11741",
"tableau.c": "false",
"tableau.h": "false",
"tableau2.d": "N/A",
"tableau2.e": "true",
"tableau2.f": "23",
"tableau2.g": "N/A"
}
]
使用此代码:
import csv
import json
file = "myFile.csv"
json_file = "myFile.json"
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}])
with open(json_file, "w") as f:
f.write(json.dumps(csv_rows, sort_keys=True, indent=4, separators=(',', ': ')))
但是我希望得到一个看起来像这样的JSON文件:
[
{
"a": "11725",
"b": "11741",
"tableau": [
{
"value" :"false",
"name" : "c"
},
{
"value" :"false",
"name" : "h"
},
]
"tableau2": [
{
"value" :"N/A",
"name" : "d"
},
{
"value" :"true",
"name" : "e"
},
{
"value" :"23",
"name" : "f"
},
{
"value" :"N/A",
"name" : "g"
},
]
}
]
我一直在寻找有关如何做到这一点的答案,到目前为止一无所获。
有关如何执行此操作的任何建议吗?
提前谢谢
答案 0 :(得分:1)
这有效:
for row in reader:
row_result = {}
for key, value in row.iteritems():
if '.' in key:
tableau, name = key.split('.')
row_result.setdefault(tableau, []).append({'value': value, 'name': name})
else:
row_result[key] = value
csv_rows.append(row_result)