Python实现JSON文件sharesTraded字段字符串转整数
解决方案
要保留原JSON结构并仅更新sharesTraded字段内的数值,你需要遍历该对象的所有键值对,逐个将带逗号的字符串转为整数,而非生成独立列表替换整个JSON。修改后的代码如下:
import json # 读取原始JSON数据 with open("AAPL22_trades.json", "r") as f: data = json.load(f) # 遍历sharesTraded的每个键,转换值为整数 shares_traded = data["sharesTraded"] for key in shares_traded: # 移除逗号并转换为整数 shares_traded[key] = int(shares_traded[key].replace(",", "")) # 将更新后的完整数据写回文件 with open("AAPL22_trades.json", "w") as f: json.dump(data, f, indent=4)
关键修改说明:
- 使用
with语句处理文件,确保文件正确关闭(比直接open更安全)。 - 直接遍历
sharesTraded的键,对每个值进行转换后直接更新原字典的对应键,而非生成新列表。 - 最后将整个
data对象(包含所有原有结构)写入文件,而非仅写入整数列表。
执行后,你的JSON文件结构会完全保留,仅sharesTraded内的数值变为整数:
{ "lastDate": { "30": "04/04/2022", "31": "04/04/2022", "40": "02/03/2022", "45": "02/01/2022" }, "transactionType": { "30": "Automatic Sell", "31": "Automatic Sell", "40": "Automatic Sell", "45": "Sell" }, "sharesTraded": { "30": 29198, "31": 105901, "40": 25000, "45": 1986 } }
内容的提问来源于stack exchange,提问作者kiestuthridge23
相关产品推荐
相关产品推荐

