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).
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).
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)
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.
https://docs.python.org/3/tutorial/datastructures.html
blacklist["blacklist"].pop(i); # `i` is the index you want to remove
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))
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..
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.
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'}}
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?