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)]
Answer from Valentin Kuhn on Stack Overflow
🌐
Like Geeks
likegeeks.com › home › python › remove elements from json arrays in python
Remove Elements from JSON arrays in Python
January 22, 2024 - The filter() function allows you to remove elements from a JSON array.
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)
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
python - Removing JSON property in array of objects - Stack Overflow
I have a JSON array that I'm cleaning up in Python. I want to remove the imageData property: More on stackoverflow.com
🌐 stackoverflow.com
How to remove a JSON object in an array with Python? - 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
How can I remove the [] from a json array of json objects?
That’s not valid json, so I doubt there is anything built in for that. You could iterate through the list yourself, convert each value in the list to json and write each row to the file separately More on reddit.com
🌐 r/learnpython
9
1
September 15, 2022
🌐
Processing
processing.org › reference › JSONArray_remove_.html
remove() / Reference / Processing.org
January 1, 2021 - // // [ // { // "id": 0, // "species": ... 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 < ...
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)
🌐
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?

Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › python-delete-json-object-from-list
How to Delete a JSON object from a List in Python | bobbyhadz
... Copied![ {"id": 1, "name": "Alice", "age": 30}, {"id": 2, "name": "Bob", "age": 35}, {"id": 3, "name": "Carl", "age": 40} ] ... We used an if statement to check if each object has an id property with a value of 2. If the condition is met, ...
🌐
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
Test with Edge Cases: Include sample data with missing keys, empty values, or empty lists to validate behavior. Removing a JSON property from an array of objects in Python is straightforward with pop(), del, or dictionary comprehensions.
🌐
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)
Top answer
1 of 3
2

You can use dict comprehension:

json_input = '''
[
  
  {
    "hostname": "bla",
    "ipaddress": "192.168.1.10",
    "subnetmask": "255.255.255.0",
    "iloip": "192.168.1.11"
   }
]
'''
desired_keys = {'hostname', 'ipaddress'}

json_filtered = json.dumps([{ k:v for (k,v) in d.items() if k in desired_keys} 
        for d in json.loads(json_input)])

print(json_filtered)

output:

'[{"hostname": "bla", "ipaddress": "192.168.1.10"}]'
2 of 3
0

I belive what you want to achieve can be done with the code given below:

import json

data_json = '{"hostname": "bla","ipaddress": "192.168.1.10","subnetmask": "255.255.255.0","iloip": "192.168.1.11"}'

data = json.loads(data_json)

chosen_fields = ['hostname', 'ipaddress']

for field in chosen_fields:
    print(f'{field}: {data[field]}')

Output:

hostname: bla
ipaddress: 192.168.1.10

Here what we do is we parse the stringified version of the json using the python's json module (i.e. json.loads(...)). Next decide on the fields we want to access (i.e. chosen_fields). Finally we iterate through the field we want to reach and get the corresponding values of the fields. This leaves the original json unmodified as you wished. Hope this helps.


Or else if you want these fields as a reduced json object:

import json

data_json = '{"hostname": "bla","ipaddress": "192.168.1.10","subnetmask": "255.255.255.0","iloip": "192.168.1.11"}'

data = json.loads(data_json)

chosen_fields = ['hostname', 'ipaddress']

reduced_json = "{" 
for field in chosen_fields:
    reduced_json += f'"{field}": "{data[field]}", '

reduced_json = list(reduced_json)
reduced_json[-2] = "}" 
reduced_json = "".join(reduced_json)
reduced = json.loads(reduced_json)

for field in chosen_fields:
    print(f'"{field}": "{reduced[field]}"')

Output:

"hostname": "bla"
"ipaddress": "192.168.1.10"

🌐
Stack Overflow
stackoverflow.com › questions › 16267197 › how-to-remove-elements-from-json-using-python
How to remove elements from JSON using Python - Stack Overflow
The data returned from the API always has a different number of elements in, and the location of 'Steve' can be in a different part of the returned string. The ID will also change. Copy(Getdata){ header = (APIResponseHeader){ sessionToken = "xxxx" } Items[] = (Summary){ Id = 1 Name = "John" TypeId = 1 }, (Summary){ Id = 2 Name = "Jack" TypeId = 1 }, (Summary){ Id = 3 Name = "Steve" TypeId = 1 }, } I think the format of the data is JSON(?) and I'm not sure how to convert, and then search it, if this is at all possible..?