Reputation: 13
I'm trying to modify a value in a JSON file, I tried the following code but it is not changing anything so I'm not sure what I'm doing wrong...
def file_filtering(file):
with open(file, 'r') as f:
data = json.load(f)
f.close()
for elem in data['features']:
elem = elem[:-1]
with open(file, 'w') as f:
json.dump(data, f, indent=4, separators=(',', ': '), sort_keys=False)
f.close()
I'm trying to change the URL by simply removing the last character '/', without deleting the values under the URL.
"features": {
"https://services.runescape.com-ow.top/weblogin/loginForm/": {
"activex_count": 0,
"addeventlistener_count": 0,
"alert_count": 0,
}
}
Upvotes: 1
Views: 44
Reputation: 8898
The problem you're having is that elem = elem[:-1]
is simply changing the elem
variable and not really changing the key of the dictionary.
Generally, changing a key from a dictionary in place is hard... It's much easier to just create a new dictionary altogether. You can do so with a dict comprehension, such as:
{key[:-1]: value for key, value in data['features'].items()}
Which you can replace in the JSON data with:
data['features'] = {
key[:-1]: value
for key, value in data['features'].items()}
You can do slightly better, rather than chopping the last character of the key, you can explicitly strip it of slashes at the end, using rstrip()
:
data['features'] = {
key.rstrip('/'): value
for key, value in data['features'].items()}
Putting it all together:
with open(file, 'r') as f:
data = json.load(f)
data['features'] = {
key.rstrip('/'): value
for key, value in data['features'].items()}
with open(file, 'w') as f:
json.dump(data, f, indent=4, separators=(',', ': '), sort_keys=False)
Note that you don't need to call f.close()
explicitly, opening a file in a context manager (as the with
statement does) takes care of closing it automatically once you leave it.
Upvotes: 2