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 Overflowhow to delete json object using python? - Stack Overflow
How to delete JSON block?
How to delete an element in a json file python - Stack Overflow
Write a python script that will delete .json files from a folder and any subfolders
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)
(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.
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)
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.
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')
Combining both jonrsharpe's and ajon's suggestions, instead of deleting it while reading, read it into memory and then write it back.
You might however have an easier time to read the jsons first and then eliminate the lines with matched elements, instead of manipulating the text directly:
json_lines = []
with open("times.json", 'r') as open_file:
for line in open_file.readlines():
j = json.loads(line)
if not j['Timestamp'] == '1234':
json_lines.append(line)
with open("times.json", 'w') as open_file:
open_file.writelines('\n'.join(json_lines))
This method gives you more conditional flexibility over multiple keys/values if necessary as opposed to looking specifically for "TimeStamp": "1234" within the line.
As suggested by @jonrsharpe, you can read in the file. Do whatever manipulations you want. Then rewrite the file.
Here is an example:
test.out:
test file
#test comment
testfile
Python code:
content = ''
with open('test.out', 'r') as f:
for line in f:
if line.startswith('#'): continue # don't copy comment lines
content += line
with open('test.out', 'w') as f:
f.write(content)
test.out after:
test file
testfile
check below code , its written with python three hence print has other syntax.
import json
d = json.loads('{ "jsonrpc": "2.0", "id": "1", "result": [ 0, {"ubus_rpc_session": "d8f4cec54d08c3f1d5581ec6135992e7","timeout": 300,"expires": 300,"acls": {"access-group": {"superuser": ["read","write"],"unauthenticated": ["read"]},"ubus": {"*": ["*"],"session": ["access","login"]},"uci": {"*": ["read","write"]}},"data": {"username": "root"}}]}')
#print d
#print(type(d['result'][1]))
i = d['result'][1]['ubus_rpc_session']
print(i)
You got an error because the value of key 'result' is a list and and 'ubus_rpc_session' is a key inside a dictionary of the list. Put simply, the value is like [int, dict].
So d['result'] gives [int, dict...]
On your first iteration, you are checking if 'ubus_rpc_session' is in int, which is wrong (so a TypeError). A possible solve to this, remove the int and get the dict element only.
value_dict = d.get("results")[1] #dict is at index 1 in the value of 'results' key
if 'ubus_rpc_session' in value_dict:
....#Do Something