我在将json数据转储到CSV文件时遇到了一个问题。CSV文件中通常会缺少一个json数据块,但是如果在控制台或文件中打印json,则可以看到该数据块。在
本质上,我调用一个服务两次,然后返回两个json响应,并将其解析并转储到CSV文件中。服务只能以7天的增量(unix时间)调用,因此我实现了在一段时间内调用该服务的逻辑。在
我使用的是python香草json
和{
首先,创建带有标题的CSV:
with open ('history_' + datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+'.csv', 'wb') as outcsv:
writer = csv.writer(outcsv)
writer.writerow(["Column1","Column2", "Column3", "Column4", "Column5",
"Column6"])
然后,我有一个计数器,它调用服务两次,五十次(在打开CSV文件之后):
^{pr2}$json响应示例:
{"Value":
[
{"ExampleName": "Test",
"ExampleNameTwo": "Test2",
"ExampleDate": "1436103790",
"ExampleCode": 00000001,
"ExampleofExample": "abcd",
"AnotherExample": "hello"},
{"ExampleName": "Test2",
"ExampleNameTwo": "Test3",
"ExampleDate": "1436103790",
"ExampleCode": 00000011,
"ExampleofExample": "abcd",
"AnotherExample": "hello2"},
]
}
CSV输出列如下所示:
ExampleName ExampleNameTwo ExampleDate ExampleCode ExampleofExample AnotherExample
最后,CSV如下:
for item in jsonResponseOne['Value']:
row = []
row.append(str(item['ExampleName'].encode('utf-8')))
if item.get("ExampleNameTwo"):
row.append(str(item["ExampleNameTwo"]))
else:
row.append("None")
row.append(str(item['ExampleDate']))
row.append(str(item['ExampleCode'].encode('utf-8')))
row.append(str(item['ExampleofExample'].encode('utf-8')))
row.append(str(item['AnotherExample'].encode('utf-8')))
writer.writerow(row)
for item in jsonResponseTwo['Value']:
anotherRow= []
anotherRow.append(str(item['ExampleName'].encode('utf-8')))
if item.get("ExampleNameTwo"):
anotherRow.append(str(item["ExampleNameTwo"]))
else:
anotherRow.append("None")
anotherRow.append(str(item['ExampleDate']))
anotherRow.append(str(item['ExampleCode'].encode('utf-8')))
anotherRow.append(str(item['ExampleofExample'].encode('utf-8')))
anotherRow.append(str(item['AnotherExample'].encode('utf-8')))
writer.writerow(anotherRow)
为什么我的CSV输出会丢失一整行数据(来自JSON响应的一块数据)?在
解决了。在
Python脚本在其中一个while循环中出现缩进问题,导致一些数据被跳过而不写入CSV文件。在
相关问题 更多 >
编程相关推荐