我有一个内容低于
的csv文件signOffDate,fundEntityType,fundId,benchmarkIds,source,returnType
30-Sep-17,ENTITY_ID,44182,MAN,IP,TR
30-Nov-17,ENTITY_ID,44182,VAN,IP,TR
我想使用python
转换为包含内容的json文件 {
"fundId": [ "44182"],
"signOffDate": "30-Sep-17",
"fundEntityType": "ENTITY_ID",
"source": "IP",
"returnType": "TR",
"benchmarkIds": [ "MAN"]
},
{
"fundId": ["44182"],
"signOffDate": "30-Nov-17",
"fundEntityType": "ENTITY_ID",
"source": "IP",
"returnType": "TR",
"benchmarkIds": [ "VAN"]
}
到目前为止我尝试过的python代码如下。它有一些问题。我被卡住了。
import csv
import json
csvfile ='sample.csv'
jsonfile ='sample.json'
def read_CSV(file, json_file):
csv_rows = []
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
for row in reader:
csv_rows.extend([{field[i]:[row[field[i]]] if field[i]=='benchmarkIds' or field[i]=='fundId' else row[field[i]] for i in range(len(field))}]);
convert_write_json(csv_rows, json_file)
#Convert csv data into json
def convert_write_json(data, json_file):
with open(json_file, "w") as f:
f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': ')))
#f.write(json.dumps(data))
read_CSV(csvfile,jsonfile)
答案 0 :(得分:1)
您需要使用append
代替extend
<强>实施例强>
import csv
import json
import pprint
with open("file", "r") as csvfile:
reader = csv.DictReader(csvfile)
field = reader.fieldnames
csv_rows = []
for row in reader:
csv_rows.append({field[i]:[row[field[i]]] if field[i]=='benchmarkIds' or field[i]=='fundId' else row[field[i]] for i in range(len(field))})
for i in csv_rows:
pprint.pprint(i)
print(json.dumps(csv_rows))
<强>输出:强>
{'benchmarkIds': ['MAN'],
'fundEntityType': 'ENTITY_ID',
'fundId': ['44182'],
'returnType': 'TR ',
'signOffDate': '30-Sep-17',
'source': 'IP'}
{'benchmarkIds': ['VAN'],
'fundEntityType': 'ENTITY_ID',
'fundId': ['44182'],
'returnType': 'TR',
'signOffDate': '30-Nov-17',
'source': 'IP'}
[{"fundId": ["44182"], "signOffDate": "30-Sep-17", "fundEntityType": "ENTITY_ID", "source": "IP", "returnType": "TR ", "benchmarkIds": ["MAN"]}, {"fundId": ["44182"], "signOffDate": "30-Nov-17", "fundEntityType": "ENTITY_ID", "source": "IP", "returnType": "TR", "benchmarkIds": ["VAN"]}]