I'm trying to change values in a JSON file from strings to integers, my issue is that the keys are row numbers so I can't call by key name (as they will change consistently). The values that need changing are within the "sharesTraded" object. Below is my JSON file:
{
"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": "29,198",
"31": "105,901",
"40": "25,000",
"45": "1,986"
}
}
And here is my current code:
import json
data = json.load(open("AAPL22_trades.json"))
dataa = data['sharesTraded']
dataa1 = dataa.values()
data1 = [s.replace(',', '') for s in dataa1]
data1 = [int(i) for i in data1]
open("AAPL22_trades.json", "w").write(
json.dumps(data1, indent=4))
However, I need the integer values to replace the string values. Instead, my code just replaces the entire JSON with the integers. I imagine there is something extra at the end that I'm missing because the strings have been changed to integers but applying it to the JSON is missing.
CodePudding user response:
You could do the following:
shares_traded = data['sharesTraded']
for key, value in shares_traded.items():
shares_traded[key] = int(value.replace(',', ''))
In this way, only the values will be changed, and the key will stay as-is.
CodePudding user response:
You have a couple of problems. First, since you only convert the values to a list, you loose the information about which key is associated with the values. Second, you write that list back to the file, loosing all of the other data too.
You could create a new dictionary with the modified values and assign that back to the original.
import json
data = json.load(open("AAPL22_trades.json"))
data['sharesTraded'] = {k:int(v.replace(',', ''))
for k,v in data['sharesTraded'].items()}
json.dump(data, open("AAPL22_trades.json", "w"), indent=4)