Skip to content Skip to sidebar Skip to footer

Handle Index Position In Python Script To Delete Json Objects From Json File - Resolved

I have a file (my_file.json) has contents as below; [ { 'use':'abcd', 'contact':'xyz', 'name':'my_script.py',

Solution 1:

Try popping in reverse order:

for x inreversed(range(len(index_list))):

Solution 2:

This will create a new list and assign only those without "name": "my_script.py" to the new list.

obj = [i for i in obj if i["name"] != "my_script.py"]

Solution 3:

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

data = [item for item indataif item.get('name') != 'my_script.py']

with open('output_my_file.json', 'w') as f:
    json.dump(data, f, indent=4)

Solution 4:

Try:

import json

    json_file = json.load(open("file.json"))

    for json_dict in json_file:
        json_dict.pop("name",None)
    print(json.dumps(json_file, indent=4))

You don't need the last line where it says 'json.dumps' I just have it there so it looks more readable when printed.

Solution 5:

As a general rule of thumb, you usually don't want to ever change an iterable while iterating over it. I suggest you save the elements you do want in the first loop:

import json

with open('path/to/file', 'r') as f:
    data = json.load(f)

items_to_keep = []
for item indata:
    if item['name'] != 'my_script.py':
        items_to_keep.append(item)

with open('path/to/file', 'w') as f:
    json.dump(items_to_keep, f, ...)

The filtering can be reduced into a single line (called list-comprehension)

import json

with open('path/to/file', 'r') as f:
    data = json.load(f)

items_to_keep = [item for item indataif item['name'] != 'my_script.py']

with open('path/to/file', 'w') as f:
    json.dump(items_to_keep, f, ...)

Post a Comment for "Handle Index Position In Python Script To Delete Json Objects From Json File - Resolved"