Skip to content
Advertisement

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

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement