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).

Answer from mdml on Stack Overflow
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)
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Trying to remove some elements from JSON data - Raspberry Pi Forums
import json response = """ {"ignoreMe": "404", "data" : [ {"name": "Bob", "language": "English"}, {"name": "Sally", "language": "German"}, [ { "language" : "deep nested" } ] ] } """ response_object = json.loads(response) print(response_object) # # recursive scanning # def scan_for_element( o, name): res = [] if isinstance(o, dict): for k in o: if k == name: res.append(o[k]) r = scan_for_element( o[k], name) res.extend( r) if isinstance(o, list): for k in o: r = scan_for_element( k, name) res.extend( r) return res result = scan_for_element(response_object, 'language') print("scan result", result)
Discussions

How to remove an element from a JSON array using Python? - Stack Overflow
I'm currently trying to make a Chromebook rental application for my high school that stores checkout information in a JSON file. Everything works except removing data from the JSON array. I found a More on stackoverflow.com
🌐 stackoverflow.com
python - Delete an element in a JSON object - Stack Overflow
I need to remove the information contained within the hours element however the information is not always the same. Some contain all the days and some only contain one or two day information. The code i've tried to use is Pyton that I have search throughout the day to use with my problem. I am not very skilled with Python. Any help would be appreciated. import json ... More on stackoverflow.com
🌐 stackoverflow.com
November 16, 2020
How do i delete an element of a json object with python? - Stack Overflow
I'm trying to delete elements from _notes that have _type as 1, but i keep getting an error and I'm not sure what it means, nor do I know how to fix it.. can anyone help me? My trimmed JSON: { ... More on stackoverflow.com
🌐 stackoverflow.com
Python Remove element from json if value exists - Stack Overflow
0 How can I remove an entire entry from a JSON file based on a match for the value of a key in Python More on stackoverflow.com
🌐 stackoverflow.com
March 30, 2017
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)
🌐
Tutorialink
python.tutorialink.com › how-to-delete-json-object-using-python
Home | Tutorialink.com
Tutorialink Provides easy to understand tutorials for most of programming language for GTU Computer Student.
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..

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 handles just the selection of a particular question in the JSON string. I had created this function because I realize for my edit and delete function I needed to select a question. Instead of repeating the code inside the edit and delete function, I could just made one function to be reused by the two functions.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-delete-json-object-from-list
How to Delete a JSON object from a List in Python | bobbyhadz
Parse the JSON object into a Python list of dictionaries. Use the enumerate() function to iterate over the list. Check if each dictionary is the one you want to remove and use the pop() method to remove the matching dict.
🌐
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
Did you mean del payload["id_pipeline"]? ... Even if it is a JSON string and not a dictionary, the easiest way is probably to parse it as a dictionary with json.loads, delete the key and write the resulting dictionary back to the JSON file.
🌐
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.

🌐
Processing
processing.org › reference › JSONArray_remove_.html
remove() / Reference / Processing.org
January 1, 2021 - // // [ // { // "id": 0, // "species": "Capra hircus", // "name": "Goat" // }, // { // "id": 1, // "species": "Panthera pardus", // "name": "Leopard" // }, // { // "id": 2, // "species": "Equus zebra", // "name": "Zebra" // } // ] JSONArray values; void setup() { values = loadJSONArray("data.json"); values.remove(0); // Remove the array's first element for (int i = 0; i < values.size(); i++) { JSONObject animal = values.getJSONObject(i); int id = animal.getInt("id"); String species = animal.getString("species"); String name = animal.getString("name"); println(id + ", " + species + ", " + name); } } // Sketch prints: // 1, Panthera pardus, Leopard // 2, Equus zebra, Zebra
🌐
Python Forum
python-forum.io › thread-31431.html
finding and deleting json object
Hi I have this JSON- { 'ticker_tape_1': [ { 'id': 1, 'Title': 'Message 1', 'txt': 'This is message 1', 'start_date': '01/04/2020', 'start_time': '16:20', 'duration': ...
🌐
YouTube
youtube.com › python tutorials for digital humanities
Deleting an Item from a JSON Database in Python (Application of Python for DH | 02) - YouTube
In this video, I answer a subscriber's question about how to delete an item from a JSON database in Python. We build upon the work in the previous video and ...
Published: June 8, 2020
Views: 6K
🌐
GitHub
gist.github.com › nlohmann › c899442d8126917946580e7f84bf7ee7
Remove empty arrays, objects or null elements from a JSON value · GitHub
Remove empty arrays, objects or null elements from a JSON value · Raw · remove_empty_elements.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.