Im using python 3 and i try to delete key and value in a json file.
settings:
{"debug": "0",
"watchdog":{
"interval": 10,
"services": {
"record": { "lag": 5 },
"gps": { "lag": 60 },
"ntp": { "lag": 120 }
}
}
}
Im trying to delete key and value from a file if key exists. My code:
import os
import json
service = "ntp"
with open('settings.json', 'r') as dataFile:
data = json.load(dataFile)
if service in data["watchdog"]["services"]:
del data["watchdog"]["services"][service]
with open('settings.json', 'w') as dataFile:
data = json.dump(data, dataFile)
Then file should look like this :
settings:
{"debug": "0",
"watchdog":{
"interval": 10,
"services": {
"record": { "lag": 5 },
"gps": { "lag": 60 },
}
}
}
Now the code runs but doesn't delete anything on the file. And i think i also should deal with the lasting comma "," in the end of the previous key value " "gps": { "lag": 60 }, " Thanks.