У меня есть CSV-файл с около тысячи строк выглядит так:
id,name,email,date_of_birth,arrive_time
4657,name1,email1,01/10/1987,15:50
7594,name2,email2,02/10/1987,10:05
Мне нужно преобразовать его в виде массива json:
[
{
"name": "name1",
"date_of_birth": "01/10/1987"
},
{
"name": "name2",
"date_of_birth": "02/10/1987"
}
]
Код, который я имеюused:
import csv
import json
file = 'myCsvFile.csv'
json_file = 'myLsonFile.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]] for i in range(len(field))}])
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(file,json_file)
Вывод этого кода
{
"name": "id;name;email;date_of_birth;arrange_time",
"date_of_birth": null
}
{
"name": "4657;name1;email1;01/10/1987;15:50",
"date_of_birth": null
}
Но я не могу понять, как выбрать определенные столбцы из CSV и создать массив.