1

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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}}}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.