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))
Answer from DevLounge on Stack Overflow
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..

Discussions

how to remove key/value pair in a json file in python - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
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
python - How to remove a key/object from a JSON file? - Stack Overflow
I want to go into the JSON file and find "class": "DepictionScreenshotsView", and remove it completely or change it to "class": "", I been at this for hours with no luck I already tried Googling but More on stackoverflow.com
🌐 stackoverflow.com
How to delete all keys from all elements of a JSON string containing specific value in a Python function - Stack Overflow
How to remove all the Keys under all elements that have a value 'NONE', so in this example busCode, effectivedate and col1. Sample Json and the python code that I tried are pasted here { "co... More on stackoverflow.com
🌐 stackoverflow.com
February 23, 2019
🌐
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' ... "Algorithms", "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 ...
🌐
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.
🌐
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.
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 71517932 › how-can-i-remove-one-element-in-a-json-string-in-python
How can I remove one element in a json string in Python? - Stack Overflow
Nakano – Nakano · 2022-03-17 ... (newest first) Date created (oldest first) 0 · You can use del function to remove the selected key from the existing dictionary....
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)
🌐
Sympathyfordata
sympathyfordata.com › doc › 3.1.0 › Library › Nodes › Data Processing › Structure › RemoveKeyJson.html
Remove key JSON — Sympathy for Data 3.1.0 documentation
Remove all occurences of key, not just first · class node_select_json.RemoveKeyJson[source] Getting started · About · Installation · Quick start · Typical workflow · Workflow elements · Workflows · Nodes · Data types · Connections · Text fields · Subflows · Lambda · Migrations · Graphical user interface · Windows · Data viewer · Node configuration · Preferences · Reporting issues · Command line interface · Command line · Nodes in python ·
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Trying to remove some elements from JSON data - Raspberry Pi Forums
Then it is up to the python code to navigate along the specific structure of the 'thing'. There is no 'select' method available as you know it in databases. ... import json response = """ {"ignoreMe": "404", "data" : [ {"name": "Bob", "language": "English"}, {"name": "Sally", "language": "German"} ] } """ response_dict = json.loads(response) print(response_dict) languages = [] for listelement in response_dict['data']: languages.append( listelement['language']) print (languages) You can write a recursive scanner and look for specific elements wherever they exist.
🌐
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.
🌐
Make Community
community.make.com › questions
Delete specific JSON keys - Questions - Make Community
December 5, 2023 - Hello, I’m kind of getting sloppy and I need your help. Normally I would figure this out but I have been working way too much… • I have a JSON string from a webflow module see screenshot 1: • I then convert this string to a JSON (not even sure if this is the right approach) see screenshot 2 : What I want to achieve is to check for each json key (exemple: 2023-12-04 and 2023-12-08 etc) if those dates have already passed.
🌐
ArduinoJson
arduinojson.org › version 6 › api › jsonobject › remove()
JsonObject::remove() | ArduinoJson 6
JsonObject::remove() removes a key-value pair from the object pointed by the JsonObject.