已经编写了一些代码,以获取包含JSON文件的目录,并创建一个新的CSV文件,以将其所有数据显示在一个位置。我想我快要到了,但是最终会收到此错误:
_csv.Error: iterable expected, not NoneType
所有JSON文件如下所示:
{
"data": [
{
"ticker": "NDX",
"tradeDate": "2017-01-03",
"expirDate": "2017-01-06",
"dte": 4,
"strike": 3300,
"stockPrice": 4900.5,
"callVolume": 0,
"callOpenInterest": 0,
"callBidSize": 10,
"callAskSize": 1,
"putVolume": 0,
"putOpenInterest": 0,
"putBidSize": 0,
"putAskSize": 2,
"callBidPrice": 1593.1,
"callValue": 1600.64,
"callAskPrice": 1607.5,
"putBidPrice": 0,
"putValue": 0,
"putAskPrice": 2.2,
"callBidIv": 0,
"callMidIv": 2.190066,
"callAskIv": 2.190066,
"smvVol": 0.160588,
"putBidIv": 0,
"putMidIv": 1.866392,
"putAskIv": 1.866392,
"residualRate": 0,
"delta": 1,
"gamma": -3.01422e-15,
"theta": -0.0470117,
"vega": 9.14631e-11,
"rho": 0.2721,
"phi": -0.404087,
"driftlessTheta": -2.29457e-8,
"extSmvVol": 0.242996,
"extCallValue": 1600.5,
"extPutValue": 0,
"spotPrice": 4900.51,
"updatedAt": "2019-04-02 10:27:11"
}
]
}
这是代码(我用来定义要处理的字段列表的示例JSON文件仅称为“输出”,位于“选项”上方的文件夹中)。 Output.csv(目标文件)也位于“选项”上方的文件夹中:
def get_list_of_json_files():
list_of_files = os.listdir('options')
return list_of_files
def create_list_from_json(out):
with open(out) as f:
data = json.load(f)
data_list = []
data_list.append(data["data"][0]["ticker"])
data_list.append(data["data"][0]["other fields"])
def write_csv():
list_of_files = get_list_of_json_files()
for file in list_of_files:
row = create_list_from_json(f'options/{file}')
with open('output.csv', 'a') as c:
writer = csv.writer(c)
writer.writerow(row)
c.close()
if __name__ == '__main__':
write_csv()