问题
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.
回答1:
You have the file open to read at the same time as you want to write. If you release the file after reading, this should work:
import os
import json
service = "ntp"
with open('settings.json', 'r') as dataFile:
data = json.load(dataFile)
# print(data)
if service in data["watchdog"]["services"]:
del data["watchdog"]["services"][service]
# print(data)
with open('settings.json', 'w') as dataFile:
data = json.dump(data, dataFile)
On the last comma, you can let the json
module handle that
回答2:
You should exit the first with
block so it can dispose of the file and let it go. I think it won't allow you to open is again for writing until you close it for reading with your first with block. You should ideally just load the data then exit the block so that file is free then do the manipulations -- this is usually a good practise; unless you have a reason to keep it open like you're reading in parts.
Here's the code for deleting the element including the comma:
In [3]: data = json.loads(strvar)
In [4]: data
Out[4]:
{'debug': '0',
'watchdog': {'interval': 10,
'services': {'record': {'lag': 5}, 'gps': {'lag': 60}, 'ntp': {'lag': 120}}}}
In [5]: if 'ntp' in data['watchdog']['services'].keys():
...: del data['watchdog']['services']['ntp']
...:
In [6]: data
Out[6]:
{'debug': '0',
'watchdog': {'interval': 10,
'services': {'record': {'lag': 5}, 'gps': {'lag': 60}}}}
来源:https://stackoverflow.com/questions/58113445/removing-nested-json-key-from-json-file-in-python