将json转换为csv NoneType问题

时间:2019-12-25 02:18:38

标签: python json csv

在将json转换为csv时,我遇到了一个问题,这是我的返回列表

msg=[{u'qALang': None, u'endDate': u'2019-12-03 16:06:28', u'language': u'EN', u'surveyId': u'SV_71AcgFo76QeXKiV', u'personId': u'666666', u'question': u'Q0', u'responseId': u'R_3I5D24ShIyrVo79', u'startDate': u'2019-12-03 16:05:46', u'surveyType': None, u'emailAddress': None, u'answer': u'1', u'finishStatus': u'1', u'responseSet': u'Default Response Set', u'surveyReference': u'test_vvvv', u'camsLeadId': u''}, {u'qALang': None, u'endDate': u'2019-12-03 16:06:28', u'language': u'EN', u'surveyId': u'SV_71AcgFo76QeXKiV', u'personId': u'99999', u'question': u'Q1a', u'responseId': u'R_3I5D24ShIyrVo79', u'startDate': u'2019-12-03 16:05:46', u'surveyType': None, u'emailAddress': None, u'answer': u'10', u'finishStatus': u'1', u'responseSet': u'Default Response Set', u'surveyReference': u'test_vvvv', u'camsLeadId': u''}]
ls=json.loads(msg)
csv_file = open(OutputCsvPath, 'a+')
csv_data = []
for item in ls:
    csv_data.append(list(item.values()))
for line in csv_data:
    csv_file.write(",".join(line) + "\n")
csv_file.close()

它将返回错误消息

  

序列项3:预期的字符串或Unicode,找到NoneType

我知道",".join(line)的使用是不正确的,但是如何避免?

1 个答案:

答案 0 :(得分:0)

join()的参数必须是字符串,但是您的某些值是None,例如u'surveyType': None。您需要将所有值转换为字符串。

for line in csv_data:
    csv_file.write(",".join(map(str, line)) + "\n")