EDIT:
This is your problem:
for element in data:
if '2-uID' in element:
del element['2-uID']
data is the top-level element, so it only has one key: "uID". Try printing out "element" :)
Maybe I'm misundertanding you, but shouldn't you just use del ?
This works for me
# string holding the JSON object
s = r"""{
"uID": {
"1-uID": {
"username": "1-username",
"pinned": true
},
"2-uID": {
"username": "2-username",
"pinned": false
},
"3-uID": {
"username": "3-username",
"pinned": false
}
}
}"""
import json
j = json.loads(s)
# remove one of the elements
del j["uID"]["2-uID"]
# see that the element is now gone
print(j)
# output:
# {'uID': {'2-uID': {'pinned': False, 'username': '2-username'},
# '3-uID': {'pinned': False, 'username': '3-username'}}}
Answer from Morten Jensen on Stack Overflow(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
returnI 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.
how to delete json object using python? - Stack Overflow
Delete Items from JSON-File - Python - Stack Overflow
How to delete particular field in a json file by using python - Stack Overflow
Write a python script that will delete .json files from a folder and any subfolders
You will have to read the file, convert it to python native data type (e.g. dictionary), then delete the element and save the file. In your case something like this could work:
import json
filepath = 'data.json'
with open(filepath, 'r') as fp:
data = json.load(fp)
del data['names'][1]
with open(filepath, 'w') as fp:
json.dump(data, fp)
I would load the file, remove the item, and then save it again. Example:
import json
with open("filename.json") as f:
data = json.load(f)
f.pop(data["names"][1]) # or iterate through entries to find matching name
with open("filename.json", "w") as f:
json.dump(data, f)
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)
It’s pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It’s done by using the json module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.
Deserialization of JSON
The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise the root object is in list or dict.
json.load(): json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
Syntax:
json.loads(file object)
Normal reading from json would be -
# Python program to read
# json file
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# saving the records array
records = data["records"]
# Iterating through the json
# list from records array
for i in data['records']:
print(i)
# Closing file
f.close()
Now according to your use case, you just need the records and no other keys from json. rather than removing it from json, you can just access it with data["records"] that would solve the issue.
However, if you still want to remove it then you can use data["records"] from json and store it in a variable. You will then have to write that into the file for persistence.
Thanks a lot, I learned something new.
Now I can continue working with the file and convert it into a CSV.
with open('data.json', 'w') as f:
json.dump(records, f)
df = pd.read_json('data.json')
df.to_csv('data.csv')
When I used GoogleTakeout to grab all my photos, when they were unzipped, there was a lot of .json files with Metadata. I put those files into my iCloud folder and while iPhotos doesn't sync that it just looked messy. But how to delete all those .json files in that folder and any subfolder in that directory?
I asked this to ChatGPT
And it did! I used VSCode to test on Windows and sure enough it deleted any files with .json in my test directory. (C:\JsonTest)
So I pointed it at my iCloud folder which had a ton of Google Photos from Takeout which exports the files and images and json files. Can't use them so I wanted them gone.
But when I ran it.. well it threw this error
I get this error when running it in a folder with lots of subfolders SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
So I asked "why is that?"
The error you are encountering is likely caused by the use of a raw string for the folder path.
Then it suggested 3 solutions once of which was
Another solution is to use a raw string by adding an 'r' before the string definition:
delete_json_files(r"C:\Users\joeblow_\Pictures\iCloud Photos\Photos")
This tells Python to interpret the string as is, without processing any escape characters.
And so I added this to the script and ran it...
And every json file in the folder and all the subfolders are now gone.
Anybody who knew Python could have done this but it was so awesome to just ask for a simple script and it worked. All via natural language.
Try this:
weapons = list(weapons_dict["weapons"])
for i, weapon in enumerate(weapons):
if (weapon['game']=="DELETE" and weapon['weapon']=="DELETE" and weapon['down']=="0" and weapon['up']=="0" and weapon['left']=="0" and weapon['right']=="0"):
del weapons_dict["weapons"][i]
That iterate over the list using i as the current index and then it will call del weapons_dict["weapons"][i] when ever it needs to delete that weapon.
Already found the solution.
The code should look like this :
def deleteWeapon():
with open('json/weapons.json') as info:
weapons_dict = json.load(info)
weapons = list(weapons_dict["weapons"])
for i, weapon in enumerate(weapons):
if (weapon['game']=="DELETE" and weapon['weapon']=="DELETE" and weapon['down']=="0" and weapon['up']=="0" and weapon['left']=="0" and weapon['right']=="0"):
weapons_dict['weapons'].pop(i)
with open('json/weapons.json','w') as remove:
json.dump(weapons_dict,remove,indent=2)
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..
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)]
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)