gpt4 book ai didi

python - 为 csv 的每行创建一个 JSON

转载 作者:行者123 更新时间:2023-12-01 02:31:26 32 4
gpt4 key购买 nike

我正在尝试弄清楚如何调整我的代码,以便它将 csv 的每一行写入自己的 json,然后将其发布(以及我想要尝试循环的方式,json 文件每次都被覆盖没有问题)。

我的代码根据需要生成结构化 json,并将所有内容格式化为正确的数据类型,但我一生都无法弄清楚如何逐行循环。我还有另一段代码可以实现第二个目标,但到目前为止,我将它们组合起来的所有尝试都失败了。

关于如何循环这段代码有什么建议吗?

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)

最佳答案

将您从 CSV 行创建的每个字典转换为 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

关于python - 为 csv 的每行创建一个 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775963/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com