如何转换csv文件以便可以JSON序列化,反之亦然?

时间:2019-02-12 08:05:35

标签: python django

我需要在celery任务中传递从网页上传的csv文件,以为csv的每一行调用一个api。但是我收到一个错误,<InMemoryUploadedFile>不可序列化

我想使用以下方法将文件转换为json:

json.dumps(unicode(self.get_form_kwargs().get('files')['uploaded_file'])) 

但是它也不起作用

views.py中:

class FileUploadView(FormView):
    template_name = 'addFile.html'
    form_class = FileUploadForm

    @method_decorator(sales_spear_login_required)
    def dispatch(self, *args, **kwargs):
        return super(FileUploadView, self).dispatch(*args, **kwargs)

    def form_valid(self, form):
        file_det = self.get_form_kwargs().get('files')['uploaded_file']
        create_dialer_report_async(self.request.user.email, file_det, list_name, campaign_name)
        return render(self.request, self.template_name, {'form': form, 'report_generated': True})

services.py中:

def create_dialer_report_async(logged_user_email, file_det, list_name, campaign_name):
create_dialer_report.apply_async((logged_user_email, file_det, list_name, campaign_name))


def create_dialer_report(user_emails, file_det, list_name, campaign_name):
reader = csv.DictReader(file_det)
for row in reader:
     # calling api from each row

它应该作为services.py中的csv文件对象提供。但是我相信这里是字符串。

1 个答案:

答案 0 :(得分:0)

类似这样的东西:

import csv
import json

csv_file = open('your_csv_file.csv', 'r')
json_file = open('your_json_file.json', 'w')

field_names = ("Your Field 1","Your Field 2","Your Field 3","Your Field 4", Your Field etc...)
reader = csv.DictReader(csv_file, field_names)

for row in reader:
    json.dump(row, json_file)
    jsonfile.write('\n')

希望这对您的需求有所帮助。