Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

python - Delete specific content in a json file

I have this json file :

{
    "help": [
        {
            "title": "",
            "date": "",
            "link": ""
        },
        {
            "title": "",
            "date": "",
            "link": ""
        },
        {
            "title": "",
            "date": "",
            "link": ""
        }
    ]
}

And I am currently struggling trying to delete each 'block' in the help list. I eventually came up with this:

import json

with open('dest_file.json', 'w') as dest_file:
    with open('source.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'help' in element:
                del element['help']
            dest_file.write(json.dumps(element))

So I was wondering how could I delete each thing in the help list, without deleting the help list. ty

question from:https://stackoverflow.com/questions/65869233/delete-specific-content-in-a-json-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes you can replace the element with an empty list:

if 'help' in element:
    element['help'] = []

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...