我正在尝试解析通过python从curl请求收到的数据。数据采用以下格式:
{'meta': {'from': '1520812800',
'granularity': 'daily',
'to': '1523232000',
'total': 6380},
'data': [{'count': 660, 'date': '2018-03-12'},
{'count': 894, 'date': '2018-03-13'}]}
最初,数据作为字符串返回可能是因为我使用response.text来检索数据。我使用ast.literal_eval(response.text)
将字符串转换为字典。我设法解析了"data"
密钥并忽略了"meta"
。目前,
data = [{"date":"2018-03-12","count":660},{"date":"2018-03-13","count":894}]}`.
我正在尝试将“date”和“count”的值导出到csv文件。在我的代码中我有这个:
keys = data[0].keys()
print("----------KEYS:---------")
print keys #['date','count']
print("------------------------")
with open('mycsv.csv','wb') as output_file:
thewriter = csv.DictWriter(output_file, fieldnames =
['date','count'])
thewriter.writeheader()
thewriter.writerow(data)
但是,python不喜欢这个并且给我一个错误:
Traceback (most recent call last):
File "curlparser.py", line 45, in <module>
thewriter.writerow(data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 152, in writerow
return self.writer.writerow(self._dict_to_list(rowdict))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 148, in _dict_to_list
+ ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: {"date":"2018-03-12","count":660},{"date":"2018-03-13","count":894}