You can just open and close the file in 'w' mode:

open('Screentime/activities.json', 'w').close()

This is going to remove completely any content from your file. In other words, your file will be empty.

EDIT: While this answer does provide the result the OP asked for, it should be noted that an empty file is not a valid JSON file. More details can be found here.

Answer from Riccardo Bucco on Stack Overflow
๐ŸŒ
PyTutorial
pytutorial.com โ€บ python-clear-json-file-python
PyTutorial | Python: Clear JSON file
September 28, 2023 - # Open a JSON file in write mode (creates the file if it doesn't exist) with open("data.json", "w") as file: # Use the `truncate()` method to clear the file's content file.truncate()
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
How to delete JSON block?
You need to shift your thinking away from "deleting" or otherwise modifying data. Instead, make a new data structure that contains what you want, then replace the old data if needed. # Get JSON file as a python dict with open("savedcomments.json", "r") as f: file_info = json.load(f) new_data = [] # Iterate through all saved comments for block in file_info["data"]: if random_word != block["randomword"]: # this is a block we want to KEEP new_data.append(block) # Overwrite the old data with the new data file_info["data"] = new_data # file_info is now up-to-date, so convert to JSON and save file with open("savedcomments.json", "w") as f: json.dump(file_info, f) In programming (and probably in life) it's usually best to check for what you WANT, not what you want to get rid of. More on reddit.com
๐ŸŒ r/learnpython
9
1
August 4, 2020
How to delete an element in a json file python - Stack Overflow
So why pass a string to loads() when you can just pass the file to load(f)? 2022-04-06T10:45:53.837Z+00:00 ... yes you are right. But i have a habit of using loads because most of the time i deal with string. 2022-04-06T10:54:06Z+00:00 ... Yes, that's fair enough. (me too) 2022-04-06T10:59:43.837Z+00:00 ... Save this answer. ... Show activity on this post. This does the right thing useing the python json ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Write a python script that will delete .json files from a folder and any subfolders
In order to prevent multiple repetitive comments, this is a friendly request to u/mda1125 to reply to this comment with the prompt they used so other users can experiment with it as well. We're also looking for new moderators, apply here Update: While you're here, we have a public discord server now โ€” We have a free ChatGPT bot on discord for everyone to use! Yes, the actual ChatGPT, not text-davinci or other models. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/ChatGPT
2
1
February 3, 2023
๐ŸŒ
Tutorialink
python.tutorialink.com โ€บ how-to-delete-json-object-using-python
Home | Tutorialink.com
Tutorialink Provides easy to understand tutorials for most of programming language for GTU Computer Student.
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 to delete json block?
r/learnpython on Reddit: How to delete JSON block?
August 4, 2020 -

(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
    return

I 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.

๐ŸŒ
GitHub
github.com โ€บ Eu-Bitwise โ€บ json-data-cleaner
GitHub - Eu-Bitwise/json-data-cleaner: A Python script to parse, clean JSON data, with error corrections. ยท GitHub
It reads JSON data from an input ... your database. ... Run the following command: python json_cleaner.py --input_file <path_to_input_file> --output_file <path_to_output_file>...
Author: Eu-Bitwise
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/chatgpt โ€บ write a python script that will delete .json files from a folder and any subfolders
r/ChatGPT on Reddit: Write a python script that will delete .json files from a folder and any subfolders
February 3, 2023 -

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.

๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_file_remove.asp
Python Delete File
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist")
๐ŸŒ
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 - Editing, Deleting and Adding Elements to a JSON file using Python How I handled Editing, Deleting and Adding Quiz Questions in a JSON file for my Simple Quiz written in Python As you remember in my โ€ฆ
๐ŸŒ
YouTube
youtube.com โ€บ python tutorials for digital humanities
Deleting an Item from a JSON Database in Python (Application of Python for DH | 02) - YouTube
In this video, I answer a subscriber's question about how to delete an item from a JSON database in Python. We build upon the work in the previous video and ...
Published: June 8, 2020
Views: 6K
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-delete-data-from-file-in-python
How to delete data from file in Python - GeeksforGeeks
April 22, 2025 - If not, it prints "Not found". This prevents errors by ensuring the file is only deleted if it exists. truncate() method is used to clear all contents of a file without deleting the file itself.
Top answer
1 of 2
2

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.

2 of 2
1

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')


๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71569463 โ€บ how-to-delete-everything-inside-an-object-in-a-json-file-but-keep-the-object
python - How to delete everything inside an object in a json file but keep the object? - Stack Overflow
I want to delete everything in ... want to clear the object. { "names": [ { "player": "Player_Name", "TB:": "12389", "BW:": "596", "SW:": "28", "CQ:": "20" } ] } ... with open('players.json', 'w') as w: with open('players.json', 'r') as r: for line in r: element = json.loads(line.strip()) if 'names' in element: del element['names'] w.write(json.dumps(element)) ... First of all find a tutorial and learn how to work (read/write) json file in python...