1

I have a Python application where the user can insert a name and one or more extensions, the final result looks like this:

{
"sets": [
{
  "name": "first",
  "extensions": ".exe"
},
{
  "name": "second",
  "extensions": [
    ".pdf",
    ".epub"
  ]
},
{
  "name": "third",
  "extensions": [
    ".mp3",
    ".mp4",
    ".wav"
  ]
}
]
}

I want to delete the entry with the name "third", and consequently the correspondent "extensions".

I have tried something like this:

def deleteJson():
    lines = []
    with open("sets.json","r") as json_file:
        for line in json_file.readlines():
            j = json.loads(line)
            if not j['name'] == "third":
               lines.append(line)
    with open("sets.json",'w') as json_file:
        json_file.writelines(join(lines))

1 Answer 1

1

Use the json library instead:

import json

with open('sets.json') as f:
    data = json.load(f)

data['sets'] = [sub for sub in data['sets'] if sub['name'] != 'third']

with open('sets.json', 'w') as f:
    json.dump(data, f)
Sign up to request clarification or add additional context in comments.

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.