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 jsonobj = 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).
🌐
Like Geeks
likegeeks.com › home › python › remove elements from json arrays in python
Remove Elements from JSON arrays in Python
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 ...
🌐
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: #this line is from my script with open('response.json', 'r') as data_file: #this line is from StackOverflow data = json.load(data_file) for element in data: element.pop('hours', None) with open('response.json', 'w') as data_file: data = json.dump(data, data_file) newData = response.json() #this line is from my script and modified it into this:
🌐
Stack Overflow
stackoverflow.com › questions › 72951553 › why-does-in-my-code-json-pop-dont-work-in-python
Why does in my code json pop dont work? (In python) - Stack Overflow
You need to read in the existing JSON, delete a key from it or whatever other modifications you want to make, and only then write it out again using json.dumps. ... can you share the code which defines the variable data? at minimum you should ...
🌐
W3Schools
w3schools.com › python › ref_list_pop.asp
Python List pop() Method
Python Examples Python Compiler ... Bootcamp Python Certificate Python Training ... The pop() method removes the element at the specified position....
Top answer
1 of 5
2
data = {'IP': {'key1': 'val1', 'key2': 'val2'}}
lst = ['IP', 'key1']

current_level = data
for key in lst[:-1]:
    current_level = current_level[key]
current_level.pop(lst[-1])

Explanation

I'll use the more complex example you provided to explain how this works. The first part of the task is to get to the dictionary from which the key should actually be removed.

{
  'IP': {
    'key1': {
      'key3': {
        'key4': 'val4',
        'key5': 'val5'
        }
      },
    'key2': 'val2'
    }
}

path = ['IP', 'key1', 'key3', 'key4']

In this example, in order to remove the key 'key4', we first need to get to the dictionary that contains this key, which is the dictionary under 'key3'. If we had this specific dictionary in a variable, say d, we could just call d.pop('key4').

'key3': {
  'key4': 'val4',
   'key5': 'val5'
  }

The path to this dictionary is data['IP']['key1']['key3']. The algorithm, instead of going directly like this, starts at the root dictionary and goes one level deeper with every iteration of the for loop. So, after the first iteration current_level is data['IP']. After the next one, it becomes data['IP']['key1']. (Because since current_level is already data['IP'], current_level = current_level['key1'] is indeed the same as data['IP']['key1'].)

This process is repeated until the needed dictionary is found. That means doing this for every element in the list that specifies the path, instead of the last one, because the last one is no more a dictionary, but a key in the dictionary that we search for. (lst[:1] is Python's way of saying all elements from lst except the last one.)

Then finally, we simply pop the necessary key (the last element in the list, in other words lst[-1]) from the dictionary to which it actually belongs, the one the algorithm found in the first step.

2 of 5
0

Maybe something like this:

def get(d, lst):
    for i in range(len(lst) - 1):
        d = d[lst[i]]
    d.pop(lst[-1])
    return data


print(get(data, lst))

Output:

{'IP': {'key2': 'val2'}}
🌐
Zyte
zyte.com › blog › json-parsing-with-python
JSON Parsing with Python [Practical Guide]
December 3, 2024 - ... Another approach to removing an element from a dictionary with JSON data is to use the pop method, which allows you to retrieve the value and use it at the same time it is removed.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-delete-json-object-from-list
How to Delete a JSON object from a List in Python | bobbyhadz
Copied!import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: my_list = json.load(f) # [{'id': 1, 'name': 'Alice'}, # {'id': 2, 'name': 'Bob'}, # {'id': 3, 'name': 'Carl'}] print(my_list) for idx, obj in enumerate(my_list): if obj['id'] == 2: my_list.pop(idx) new_file_name = 'new-file.json' with open(new_file_name, 'w', encoding='utf-8') as f: f.write(json.dumps(my_list, indent=2)) The code sample shows how to delete a JSON object from an array of objects in a file.
Find elsewhere
🌐
W3Schools
w3schools.com › python › ref_dictionary_pop.asp
Python Dictionary pop() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.pop("model") print(car) Try it Yourself »
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)
🌐
freeCodeCamp
freecodecamp.org › news › python-pop-how-to-pop-from-a-list-or-an-array-in-python
Python .pop() – How to Pop from a List or an Array in Python
March 1, 2022 - This means that when the pop() method doesn't have any arguments, it will remove the last list item. So, the syntax for that would look something like this: ... #list of programming languages programming_languages = ["Python", "Java", "JavaScript"] #print initial list print(programming_languages) #remove last item, which is "JavaScript" programming_languages.pop() #print list again print(programming_languages) #output #['Python', 'Java', 'JavaScript'] #['Python', 'Java']
🌐
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?
June 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?

🌐
Python Guides
pythonguides.com › json-data-in-python
How To Get Values From A JSON Array In Python?
November 29, 2024 - State: California Capital: Sacramento Population: 39512223 --- State: Texas Capital: Austin Population: 28995881 --- State: Florida Capital: Tallahassee Population: 21477737 --- ... Let me show you another way to extract values from a JSON array is: by using list comprehension. List comprehension allows you to create a new list based on an existing list or iterable. Here’s an example: import json # Load JSON data from file with open('C:/Users/fewli/Downloads/Python/states.json') as file: data = json.load(file) state_names = [state['name'] for state in data] print("State Names:", state_names)
🌐
Bomberbot
bomberbot.com › python › python-pop-how-to-pop-from-a-list-or-an-array-in-python
Python .pop() – How to Pop from a List or an Array in Python - Bomberbot
The pop() method is called on a list (or array) object using dot notation, like so: ... The index argument is optional. When omitted, pop() removes and returns the last item in the list. If index is provided, pop() removes and returns the item at that specific index.
🌐
GeeksforGeeks
geeksforgeeks.org › python › loop-through-a-json-array-in-python
Loop through a JSON array in Python - GeeksforGeeks
July 23, 2025 - You can loop through a JSON array in Python by using the json module and then iterating through the array using a for loop.
🌐
Tutorialspoint
tutorialspoint.com › python › python_array_pop_method.htm
Python Array pop() Method
Array Elements Before Poping : array('i', [100, 220, 330, 540]) Array Elements After Poping : array('i', [100, 220, 540]) If we do not pass any argument to this method, it removes the last element i.e -1 element from an array.
🌐
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 - Below are the possible approaches to Remove items from a JSON file In Python: Using the pop() method · Using dictionary comprehension · Using the del statement · Using the update() method ·