Home > OS >  How to delete everything inside an object in a json file but keep the object?
How to delete everything inside an object in a json file but keep the object?

Time:03-23

I want to delete everything in the object "name" in the given json file example but keep the the object, in simple words I want to clear the object.

{

    "names": [

        {

            "player": "Player_Name",

            "TB:": "12389",

            "BW:": "596",

            "SW:": "28",

            "CQ:": "20"

        }

    ]

}

I used tried this code:

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

but it just clears the whole json file

sorry for my bad english

CodePudding user response:

The problem is that you open the same file twice - for reading and for writing simultaneously. Also a JSON cannot be parsed line by line, only as a whole.

import json

# 1. read
with open('players.json', 'r') as r:
    data = json.load(r)

# 2. modify
# (you might want to check if data is a dict)
data['names'] = []


# 3. write
with open('players.json', 'w') as w:
    data = json.dump(data, w)
  • Related