Assuming, the file in which you have your JSON is called file.json:

import json
with open('file.json') as f:
    d = json.load(f)
    for key, value in d.items():
        del value['id']
        d[key] = value

Alternative you can use the following:

import json
with open('file.json') as f:
    d = json.load(f)
    for key, value in d.items():
        value.pop('id', None) // this will not crash if the element has no key 'id'
Answer from lmiguelvargasf on Stack Overflow
🌐
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' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'} output.json { "website": "GeeksforGeeks", "topics": [ "Algorithms", "Data Structures", "Python", "JavaScript" ] } In this example, we are using dictionary comprehension to remove a specified key, "featured_article", from a JSON file (input.json).
Discussions

python - Delete an element in a JSON object - Stack Overflow
I am trying to loop through a list of objects deleting an element from each object. Each object is a new line. I am trying to then save the new file as is without the element contained within the o... More on stackoverflow.com
🌐 stackoverflow.com
November 16, 2020
Python, delete JSON element having specific key from a loop - Stack Overflow
Related: Remove element from JSON list... ... juanpa.arrivillaga, thank you, your explanation "that variable is simply re-created" brings the light here. I see one workaround: copy all elements except 'bad' to newly created collection, and then substitute it instead of old one. Not optimal solution but I'll use it if no easier approach is suggested by someone. ... One of approaches from Remove element from list when using enumerate() in python ... More on stackoverflow.com
🌐 stackoverflow.com
September 5, 2018
python - Removing JSON property in array of objects - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
October 7, 2018
Removing JSON key from file in python - Stack Overflow
if 'idb_metric' in element["fields"]: ... print(element) ... Sign up to request clarification or add additional context in comments. ... Thanks, that worked but then next question is how to find/delete multiple keys. Updated question accordingly. 2018-10-24T23:50:37.813Z+00:00 ... Find the answer to your question by ... More on stackoverflow.com
🌐 stackoverflow.com
October 25, 2018
🌐
Like Geeks
likegeeks.com › home › python › remove elements from json arrays in python
Remove Elements from JSON arrays in Python
January 22, 2024 - In this example, the “Standard” package, which is at index 1, is removed and returned. The .remove() method allows you to remove a JSON element based on its value rather than its index · Suppose you want to remove a specific package by its value.
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..

🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Trying to remove some elements from JSON data - Raspberry Pi Forums
with requests.request('get', 'api.openweathermap.org/data/2.5/weather', timeout=30, headers=headers) as response: data = response.json() for element in data: element.pop('pressure', None) element.pop('humidity', None) newData = data But it won't run, returning error: AttributeError: 'str' object ...
🌐
Bobby Hadz
bobbyhadz.com › blog › python-delete-json-object-from-list
How to Delete a JSON object from a List in Python | bobbyhadz
The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value. The lambda function we passed to filter() gets called with each dictionary of the list. The lambda checks if the name key in each dictionary doesn't have a specific value.
🌐
CopyProgramming
copyprogramming.com › howto › how-to-remove-key-value-pair-in-a-json-file-in-python
Removing Key-Value Pairs from JSON Files in Python: Complete 2026 Guide
November 26, 2025 - Removing keys from all array elements requires mapping the removal function across the list. import json def clean_array(data, keys_to_remove): if isinstance(data, list): return [ {k: v for k, v in item.items() if k not in keys_to_remove} if isinstance(item, dict) else item for item in data ] elif isinstance(data, dict): return {k: clean_array(v, keys_to_remove) for k, v in data.items() if k not in keys_to_remove} return data # Example: Remove 'id' and 'timestamp' from all user records with open('users.json', 'r') as f: users = json.load(f) # Assume this is a list of user objects cleaned_users = clean_array(users, {'id', 'timestamp'}) with open('users_cleaned.json', 'w') as f: json.dump(cleaned_users, f, indent=2)
Find elsewhere
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)
🌐
CopyProgramming
copyprogramming.com › howto › python-remove-key-from-json-javascript-code-example
Remove Key from JSON: Python & JavaScript Methods, 2026 Best Practices
December 14, 2025 - JavaScript best practice: Prefer Object.fromEntries() with filter() for immutability; use ES6 destructuring for single-key removal in modern codebases. File safety: Always use file.truncate() in Python when writing back to files opened in read-write mode to prevent corruption. 2026 standard: Implement immutability-first approaches; never mutate original JSON objects directly in reactive frameworks or concurrent environments.
🌐
GitHub
gist.github.com › usmansbk › 3d44c7228fa8cfe8097daa2f7e2b476c
Recursively remove json keys in an array · GitHub
Recursively remove json keys in an array. GitHub Gist: instantly share code, notes, and snippets.
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)
🌐
w3tutorials
w3tutorials.net › blog › removing-json-property-in-array-of-objects
How to Remove a JSON Property from an Array of Objects in Python: Fixing Empty List Comprehension Issues — w3tutorials.net
Why this works: The inner dictionary comprehension {key: value ...} creates a new dict with all keys except "email". The outer list comprehension collects these new dicts into users_without_email. Best for: When you need to preserve the original data (e.g., logging, auditing). A list comprehension that returns an empty list (e.g., []) is a frequent frustration. Let’s diagnose the root causes. Problem: Adding a condition (if) to the list comprehension, which filters out elements instead of modifying them.
🌐
CopyProgramming
copyprogramming.com › howto › how-to-remove-json-object-key-and-value
Python: Eliminating a JSON Object's Key and Value: A Guide
April 19, 2023 - How to remove json key value pair from json object, First, your Data is JSONArray, retrieving that by jsonObj.getJSONArray ("Data"), then access the array with get (0) [assuming, your array will contain only one entry like your example] and finally, removing that key by remove method.
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-12.php
Python: Remove a key from a dictionary - w3resource
June 28, 2025 - # Create a dictionary 'myDict' with key-value pairs. myDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4} # Print the original dictionary 'myDict'. print(myDict) # Check if the key 'a' exists in the 'myDict' dictionary. if 'a' in myDict: # If 'a' is in ...