import csv
import json
def csv_to_json(csvFilePath):
jsonArray = []
decoded_file = csvFilePath.read().decode('utf-8').splitlines()
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(decoded_file)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
option = [row['option1'], row['option2'], row['option3'], row['option4']]
option = filter(None, option)
newJson = {
'numb': row['numb'],
'question': row['question'],
'answer': row['answer'],
'options': option
}
jsonArray.append(newJson)
print('>>>>>>>jsonArray>>>>>>>', jsonArray)
jsonString = json.dumps(jsonArray)
print('>>>>>>>jsonString>>>>>>>', jsonString)
return jsonArray
Run Code Online (Sandbox Code Playgroud)
错误
TypeError at /path/path
Object of type filter is not JSON serializable
>>>>>>>jsonArray>>>>>>> [{'numb': '1', 'question': 'What does HTML stand for?', 'answer': 'Hyper Text Markup Language', 'options': <filter object at 0x7f3d3459fa00>}, {'numb': '2', 'question': 'What does CSS stand for?', 'answer': 'Cascading Style Sheet', 'options': <filter object at 0x7f3d34317400>}]
Run Code Online (Sandbox Code Playgroud)
如果我# 'options': option从那时起评论newJson它就完美了
正如错误所述,过滤器对象不可序列化。
但有一个清单是
'options': list(option)
Run Code Online (Sandbox Code Playgroud)
但是,我不太清楚您要过滤的内容。具有 None 类型的列表将在 JSON 数组中变为 null
| 归档时间: |
|
| 查看次数: |
2095 次 |
| 最近记录: |