Well... if blacklist is your json, then why not do the following?

# If you know the value to be removed:
blacklist['blacklist'].remove(225915965769121792)
# Or if you know the index to be removed (pop takes an optional index, otherwise defaults to the last one):
blacklist['blacklist'].pop()
# Or
del blacklist['blacklist'][0]  # 0 or any other valid index can be used.
Answer from Sam Chats on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how can i remove the [] from a json array of json objects?
r/learnpython on Reddit: How can I remove the [] from a json array of json objects?
September 15, 2022 -

I have to dump a bunch of json objects to a file like this

list_content = [] 
with open("mylist.json", "w") as f:
        json.dump(list_content, f, indent=4)

The json looks like this

[
{ "ABC" : [$content]},
{ "DEF" : [$content]}
]

But i need it too look like this

{

"ABC" : [$content] , "DEF" : [$content]

}

How can I achieve it where it can dump to a file without the square brackets?

Discussions

how to delete json object using python?
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 JSON file. My JSON file is: I want to delete the JSON object with ename mark. As I am new to python More on python.tutorialink.com
🌐 python.tutorialink.com
1
Python Remove element from json if value exists - Stack Overflow
0 removing json items from array if value is duplicate python More on stackoverflow.com
🌐 stackoverflow.com
March 30, 2017
Python, delete JSON element having specific key from a loop - Stack Overflow
Using Python, I need to delete all objects in JSON array that have specific value of 'name' key. However, I can't do that from a loop. Imaging I want to delete all items having 'bad' as name in the More on stackoverflow.com
🌐 stackoverflow.com
September 5, 2018
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
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)
🌐
Like Geeks
likegeeks.com › home › python › remove elements from json arrays in python
Remove Elements from JSON arrays in Python
January 22, 2024 - The pop() method not only removes the last element from the array but also returns it. This method is useful when you need to work with the removed element afterwards. ... Also, you can use pop() with a specific index to remove an element from ...
🌐
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.
🌐
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"}]}' response_dict = json.loads(response) print(response_dict) print(response_dict['data']['language'])
Find elsewhere
🌐
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
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)
🌐
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': ...
🌐
CSDN
devpress.csdn.net › python › 630461c97e6682346619ad23.html
how to delete json object using python? - DevPress官方社区
August 23, 2022 - 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).
🌐
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.
🌐
GitHub
gist.github.com › gkhays › 4fe1e6193e62b1f2cad3bd4b00f16c92
Remove an attribute or element from a JSON array during enumeration · GitHub
July 18, 2018 - JSONArray nameArray = firstJSON.names(); List<String> keyList = new ArrayList<String>(); for (int i = 0; i < nameArray.length(); i++) { keyList.add(nameArray.get(i).toString()); } for (int i = 0; i < ja.length(); i++) { for (String key : keyList) { JSONObject json = ja.getJSONObject(i); if (json.getString(key).equals("null")) { json.remove(key); } } }