我正在试图弄清楚如何调整我的代码,以便它将csv的每一行写入自己的json,然后将其发布(我想要尝试循环这个,json文件)每次被覆盖都没有问题。)
我的代码生成结构化的jsons,因为我需要它并将所有内容格式化为正确的数据类型,但我不能为我的生活找出如何循环这一行。我有另一段代码可以实现第二个目标,但到目前为止,我所有尝试组合它们的尝试都失败了。
关于如何循环使用此代码的任何建议?
output = []
with open('Test3.csv') as csv_file:
for a in csv.DictReader(csv_file):
output.append({
'OrderType': a['OrderType'],
'OrderStatus': a['OrderStatus'],
'OrderDateTime': a['OrderDateTime'],
'SettlementDate': a['SettlementDate'],
'MarketId': int(a['MarketId']),
'OrderRoute': a['OrderRoute'],
'OrderEntityType': a['OrderEntityType'],
'SecurityId': a['SecurityId'],
'CurrencyISOCode': a['CurrencyISOCode'],
'Price': float(a['Price']),
'TotalCommission': float(a['TotalCommission']),
'SettlementStatus': a['SettlementStatus'],
'QuantitySettled': float(a['QuantitySettled']),
'SecurityOrderAllocations': {
'Reference': a['Account Number'],
'InvestmentCollectiveId': a['Account Number'],
'NominalAmount': float(a['QuantitySettled']),
'InvestmentAmount': float(a['InvestmentAmount']),
'OpenNominal': float(a['QuantitySettled']),
'SettlementCurrencyISOCode': 'USD',
'SettlementAccountId': a['Account Number'],
'OrderToSettlementExchangeRate': float('1'),
'SettlementToPortfolioExchangeRate': float('1'),
'OrderToPortfolioExchangeRate': float('1')
}
})
output_json = json.dumps(output)
with open ('Test.json', 'w') as f:
f.write(output_json)
答案 0 :(得分:2)
将您从CSV行创建的每个dict转换为JSON,并将其写入文件(或将其POST到URL,或者您想用它做什么)。
filenum = 1
with open('Test3.csv') as csv_file:
for a in csv.DictReader(csv_file):
json = json.dumps({
'OrderType': a['OrderType'],
'OrderStatus': a['OrderStatus'],
'OrderDateTime': a['OrderDateTime'],
'SettlementDate': a['SettlementDate'],
'MarketId': int(a['MarketId']),
'OrderRoute': a['OrderRoute'],
'OrderEntityType': a['OrderEntityType'],
'SecurityId': a['SecurityId'],
'CurrencyISOCode': a['CurrencyISOCode'],
'Price': float(a['Price']),
'TotalCommission': float(a['TotalCommission']),
'SettlementStatus': a['SettlementStatus'],
'QuantitySettled': float(a['QuantitySettled']),
'SecurityOrderAllocations': {
'Reference': a['Account Number'],
'InvestmentCollectiveId': a['Account Number'],
'NominalAmount': float(a['QuantitySettled']),
'InvestmentAmount': float(a['InvestmentAmount']),
'OpenNominal': float(a['QuantitySettled']),
'SettlementCurrencyISOCode': 'USD',
'SettlementAccountId': a['Account Number'],
'OrderToSettlementExchangeRate': float('1'),
'SettlementToPortfolioExchangeRate': float('1'),
'OrderToPortfolioExchangeRate': float('1')
}
})
with open('Test' + str(filenum) + '.csv', 'w') as f:
f.write(json)
filenum += 1