EDIT:

This is your problem:

for element in data:
    if '2-uID' in element:
        del element['2-uID']

data is the top-level element, so it only has one key: "uID". Try printing out "element" :)


Maybe I'm misundertanding you, but shouldn't you just use del ?

This works for me

# string holding the JSON object
s = r"""{
    "uID": {
        "1-uID": {
            "username": "1-username",
            "pinned": true
        },
        "2-uID": {
            "username": "2-username",
            "pinned": false
        },
        "3-uID": {
            "username": "3-username",
            "pinned": false
        }
    }
}"""

import json

j = json.loads(s)

# remove one of the elements
del j["uID"]["2-uID"]

# see that the element is now gone
print(j)

# output:
# {'uID': {'2-uID': {'pinned': False, 'username': '2-username'},
#          '3-uID': {'pinned': False, 'username': '3-username'}}}
Answer from Morten Jensen on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how to delete json block?
r/learnpython on Reddit: How to delete JSON block?
August 4, 2020 -

(Crosspost from r/redditdev.)

Hi!

I’m developing a Reddit bot that saves some comments that it finds to a JSON File and later uses them again and am using the following code to look through a JSON file called savedcomments.json where it looks for different entries (blocks) in the data bracket.

# Get JSON file as a python dict
with open("savedcomments.json", "r") as f:
    file_info = json.load(f)
# Iterate through all saved comments
for block in file_info["data"]:
    block_random_word = block["randomword"]
    if (random_word == block_random_word):
    (…)

# Append comment_data to the dict
file_info["data"].append(comment_data)

# Convert dict to JSON and save file
with open("savedcomments.json", "w") as f:
    json.dump(file_info, f)
   (…)

I want to delete the entire block for a specific comment (entry) after it’s been used but don’t know how as I’m still a relative beginner to Python (I really need to learn more and take some courses!).

This is what I came up with, but I doubt it works because it’s just a guess:

for block in file_info["data"]:
    del block
    return

I don’t know if that’d work, but it probably wouldn’t. Any help would be fantastically appreciated! 💙

More detailed information about my request in this comment.

Discussions

how to delete json object using python? - Stack Overflow
I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the J... More on stackoverflow.com
🌐 stackoverflow.com
Delete Items from JSON-File - Python - Stack Overflow
It’s done by using the json module, ... help us to read the JSON file. ... The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() method is used for it. If you have used JSON data from another program or obtained ... More on stackoverflow.com
🌐 stackoverflow.com
How to delete particular field in a json file by using python - Stack Overflow
2.Here is the code for implementation. Firstly just open the JSON file and load the data. Then to check if the key "data" and "UserName" are in it or not. If yes, delete these keys and their value. More on stackoverflow.com
🌐 stackoverflow.com
Write a python script that will delete .json files from a folder and any subfolders
In order to prevent multiple repetitive comments, this is a friendly request to u/mda1125 to reply to this comment with the prompt they used so other users can experiment with it as well. We're also looking for new moderators, apply here Update: While you're here, we have a public discord server now — We have a free ChatGPT bot on discord for everyone to use! Yes, the actual ChatGPT, not text-davinci or other models. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/ChatGPT
2
1
February 3, 2023
Top answer
1 of 5
29

Here's a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.

#!/usr/bin/python                                                               

# Load the JSON module and use it to load your JSON file.                       
# I'm assuming that the JSON file contains a list of objects.                   
import json
obj  = json.load(open("file.json"))

# Iterate through the objects in the JSON and pop (remove)                      
# the obj once we find it.                                                      
for i in xrange(len(obj)):
    if obj[i]["ename"] == "mark":
        obj.pop(i)
        break

# Output the updated file with pretty JSON                                      
open("updated-file.json", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)

The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you've reached the end of the for loop (you don't want to modify the list while you iterate through it).

2 of 5
12

The proper way to json is to deserialize it, modify the created objects, and then, if needed, serialize them back to json. To do so, use the json module. In short, use <deserialized object> = json.loads(<some json string>) for reading json and <json output> = json.dumps(<your object>) to create json strings. In your example this would be:

import json
o = json.loads("""[
    {
        "ename": "mark",
        "url": "Lennon.com"
    },
    {
        "ename": "egg",
        "url": "Lennon.com"
    }
]""")
# kick out the unwanted item from the list
o = filter(lambda x: x['ename']!="mark", o)
output_string = json.dumps(o)
Top answer
1 of 2
2

It’s pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It’s done by using the json module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

Deserialization of JSON

The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise the root object is in list or dict.

json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.

Syntax:

json.loads(file object)

Normal reading from json would be -

# Python program to read 
# json file 


import json 

# Opening JSON file 
f = open('data.json',) 

# returns JSON object as  
# a dictionary 
data = json.load(f) 

# saving the records array
records = data["records"]

# Iterating through the json 
# list from records array
for i in data['records']: 
    print(i) 

# Closing file 
f.close() 

Now according to your use case, you just need the records and no other keys from json. rather than removing it from json, you can just access it with data["records"] that would solve the issue.

However, if you still want to remove it then you can use data["records"] from json and store it in a variable. You will then have to write that into the file for persistence.

2 of 2
1

Thanks a lot, I learned something new.

Now I can continue working with the file and convert it into a CSV.

with open('data.json', 'w') as f:
    json.dump(records, f)

df = pd.read_json('data.json')
df.to_csv('data.csv')


🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-remove-key-value-pair-from-a-json-file-in-python
How to Remove Key-Value Pair from a JSON File in Python - GeeksforGeeks
July 23, 2025 - Removed key 'featured_article' ... "Data Structures", "Python", "JavaScript" ] } In this example, we have used the del statement to remove a specified key, "featured_article", from JSON data loaded from a file named ...
Find elsewhere
🌐
Medium
mae-morano-64788.medium.com › editing-deleting-and-adding-elements-to-a-json-file-using-python-5615ea6a0ace
Editing, Deleting and Adding Elements to a JSON file using Python | by Mae Morano | Medium
September 29, 2020 - This function simply does one thing and that is to delete an entire question in the JSON file. It will delete including the choices and answers. You might be wondering why in every function I have above, it always end calling the game_on() function. The reason is after every execution of the function above, I want it to return to the main function executing the whole game which is the game_on() function. I had learned alot from this quiz exercise and actually discovered how useful creating functions are in a project since you can reuse them again and again.
🌐
Reddit
reddit.com › r/chatgpt › write a python script that will delete .json files from a folder and any subfolders
r/ChatGPT on Reddit: Write a python script that will delete .json files from a folder and any subfolders
February 3, 2023 -

When I used GoogleTakeout to grab all my photos, when they were unzipped, there was a lot of .json files with Metadata. I put those files into my iCloud folder and while iPhotos doesn't sync that it just looked messy. But how to delete all those .json files in that folder and any subfolder in that directory?

I asked this to ChatGPT  

And it did! I used VSCode to test on Windows and sure enough it deleted any files with .json in my test directory. (C:\JsonTest)

So I pointed it at my iCloud folder which had a ton of Google Photos from Takeout which exports the files and images and json files. Can't use them so I wanted them gone.

But when I ran it.. well it threw this error

I get this error when running it in a folder with lots of subfolders SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

So I asked "why is that?"

The error you are encountering is likely caused by the use of a raw string for the folder path.

Then it suggested 3 solutions once of which was
Another solution is to use a raw string by adding an 'r' before the string definition:

delete_json_files(r"C:\Users\joeblow_\Pictures\iCloud Photos\Photos")

This tells Python to interpret the string as is, without processing any escape characters.

And so I added this to the script and ran it...

And every json file in the folder and all the subfolders are now gone.

Anybody who knew Python could have done this but it was so awesome to just ask for a simple script and it worked. All via natural language.

🌐
Stack Overflow
stackoverflow.com › questions › 32956837 › python-deleteing-data-from-a-json-module-file
Python : Deleteing data from a JSON module file - Stack Overflow
I currently have this code which works fine, but I need to be able to delete data on command from the data file. This is what the inside of the file looks like: [[15, "TomBy012"], [10, "Badrob135"]] ... Copyimport json def load_scores(): with open("scores.json") as infile: return json.load(infile) def save_scores(scores): with open("scores.json", "w") as outfile: json.dump(scores, outfile) print("Scores Saved") def scoresMenu(): print ("""Please pick a valid option from the list below 1 » Load existing scores from the database 2 » Save the scores from this session 3 » Create a new score for
🌐
Stack Overflow
stackoverflow.com › questions › 74739365 › python-script-to-remove-all-data-from-values-in-a-the-json-file
Python script to remove all data from values in a the Json file - Stack Overflow
December 9, 2022 - Been searching the forums for this query, and seems fairly straightforward how would I remove all the data from values in JSON file to NULL or "", using python? ... { “StringProperty”: “StringValue”, “NumberProperty”: 10, “FloatProperty”: 20.13, “BooleanProperty”: true, “EmptyProperty”: null } Example of JSON after python script run. { “StringProperty”: “NumberProperty”: “FloatProperty”: “BooleanProperty”: “EmptyProperty”: } ... def del_none(N): """ Delete keys with the value ``None`` in a dictionary, recursively.
Top answer
1 of 2
95

Let's assume you want to overwrite the same file:

import json

with open('data.json', 'r') as data_file:
    data = json.load(data_file)

for element in data:
    element.pop('hours', None)

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

dict.pop(<key>, not_found=None) is probably what you where looking for, if I understood your requirements. Because it will remove the hours key if present and will not fail if not present.

However I am not sure I understand why it makes a difference to you whether the hours key contains some days or not, because you just want to get rid of the whole key / value pair, right?

Now, if you really want to use del instead of pop, here is how you could make your code work:

import json

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

for element in data:
    if 'hours' in element:
        del element['hours']

with open('data.json', 'w') as data_file:
    data = json.dump(data, data_file)

EDIT So, as you can see, I added the code to write the data back to the file. If you want to write it to another file, just change the filename in the second open statement.

I had to change the indentation, as you might have noticed, so that the file has been closed during the data cleanup phase and can be overwritten at the end.

with is what is called a context manager, whatever it provides (here the data_file file descriptor) is available ONLY within that context. It means that as soon as the indentation of the with block ends, the file gets closed and the context ends, along with the file descriptor which becomes invalid / obsolete.

Without doing this, you wouldn't be able to open the file in write mode and get a new file descriptor to write into.

I hope it's clear enough...

SECOND EDIT

This time, it seems clear that you need to do this:

with open('dest_file.json', 'w') as dest_file:
    with open('source_file.json', 'r') as source_file:
        for line in source_file:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            dest_file.write(json.dumps(element))
2 of 2
2
with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

Top answer
1 of 3
3

First question

However, whenever there's more than two elements and I enter anything higher than two, it doesn't delete anything. Even worse, when I enter the number one, it deletes everything but the zero index(whenever the array has more than two elements in it).

Inside delete_data() you have two lines reading i = + 1, which just assignes +1 (i.e., 1) to i. Thus, you're never increasing your index. You probably meant to write either i = i+1 or i += 1.

def delete_data():    # Deletes an element from the array
    view_data()
    new_data = []
    with open(filename, "r") as f:
        data = json.load(f)
        data_length = len(data) - 1
    print("Which index number would you like to delete?")
    delete_option = input(f"Select a number 0-{data_length}: ")
    i = 0
    for entry in data:
        if i == int(delete_option):
            i += 1  # <-- here
        else:
            new_data.append(entry)
            i += 1  # <-- and here

    with open(filename, "w") as f:
        json.dump(new_data, f, indent=4)

Second question: further improvements

Is there a better way to implement that in my Python script?

First, you can get rid of manually increasing i by using the builtin enumerate generator. Second, you could make your functions reusable by giving them parameters - where does the filename in your code example come from?

# view_data() should probably receive `filename` as a parameter
def view_data(filename: str):   # Prints JSON Array to screen
    with open(filename, "r") as f:
        data = json.load(f)
        # iterate over i and data simultaneously
        # alternatively, you could just remove i
        for i, item in enumerate(data):
            name = item["name"]
            chromebook = item["chromebook"]
            check_out = item["time&date"]
            print(f"Index Number: {i}")
            print(f"Name : {name}")
            print(f"Chromebook : {chromebook}")
            print(f"Time Of Checkout: {check_out} ")
            print("\n\n")
            # not needed anymore: i = i + 1

# view_data() should probably receive `filename` as a parameter
def delete_data(filename: str):    # Deletes an element from the array
    view_data()
    new_data = []
    with open(filename, "r") as f:
        data = json.load(f)
        data_length = len(data) - 1
    print("Which index number would you like to delete?")
    delete_option = input(f"Select a number 0-{data_length}: ")
    # iterate over i and data simultaneously
    for i, entry in enumerate(data):
        if i != int(delete_option):
            new_data.append(entry)

    with open(filename, "w") as f:
        json.dump(new_data, f, indent=4)

Furthermore, you could replace that for-loop by a list comprehension, which some may deem more "pythonic":

new_data = [entry for i, entry in enumerate(data) if i != int(delete_option)]
2 of 3
3

There are easier ways to delete an element by index from a Python list.

Given li = ["a", "b", "c"], you can delete element 1 ("b") by index in (at least) the following ways:

li.pop(1) # pop takes an index (defaults to last) and removes and returns the element at that index

del li[1] # the del keyword will also remove an element from a list

So, here's some updated code:

def view_data():   # Prints JSON Array to screen
    with open(filename, "r") as f:
        data = json.load(f)
        i = 0
        for item in data:
            name = item["name"]
            chromebook = item["chromebook"]
            check_out = item["time&date"]
            print(f"Index Number: {i}")
            print(f"Name : {name}")
            print(f"Chromebook : {chromebook}")
            print(f"Time Of Checkout: {check_out} ")
            print("\n\n")
            i = i + 1

def delete_data():    # Deletes an element from the array
    view_data()
    with open(filename, "r") as f:
        data = json.load(f)
        data_length = len(data) - 1
    print("Which index number would you like to delete?")
    delete_option = input(f"Select a number 0-{data_length}: ")
    del data[int(delete_option)] # or data.pop(int(delete_option))

    with open(filename, "w") as f:
        json.dump(data, f, indent=4)
🌐
Stack Overflow
stackoverflow.com › questions › 71569463 › how-to-delete-everything-inside-an-object-in-a-json-file-but-keep-the-object
python - How to delete everything inside an object in a json file but keep the object? - Stack Overflow
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) ... Sign up to request clarification or add additional context in comments.
🌐
PyTutorial
pytutorial.com › python-clear-json-file-python
PyTutorial | Python: Clear JSON file
September 28, 2023 - # Open a JSON file in append mode ("a" mode) with open("data.json", "a") as file: # Use the `truncate()` method to clear the file's content file.truncate() ... Note: The second example opens the file in "append" mode and then truncates it.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-delete-json-object-from-list
How to Delete a JSON object from a List in Python | bobbyhadz
The file called new-file.json reflects the changes and the original file remains unchanged. ... You can also use a list comprehension to delete a JSON object from a list.
🌐
Like Geeks
likegeeks.com › home › python › remove elements from json arrays in python
Remove Elements from JSON arrays in Python
January 22, 2024 - Learn to remove elements from JSON arrays in Python with this tutorial. Explore methods like index, value-based, conditional removal, and more.