How would i delete something from a json file - python

I'm not sure how to delete something from a .json file
I've tryed looking it up and it still nothing :(
#bot.command()
async def afkremoveme(ctx):
#pls help me I'm lost!
no errors

I'm not sure what you want your command to do, but here's an example of how you would implement json into discord.py.
Here, whenever the command is executed, the bot opens a json file, reads the data, and sees if the message author is in the data. If the author is in the data, the key/value pair is deleted, and the data is rewritten into the json file:
import json
#bot.command()
async def afkremoveme(ctx):
f = "yourFile.json"
author = str(ctx.author.id)
with open(f, "r") as read_file:
data = json.load(read_file)
if author in data: # if any key in the dictionary is an integer, it is converted to a string when a json file is written
del data[author]
newData = json.dumps(data, indent=4)
with open(f, "w") as write_file:
write_file.write(newData)
await ctx.send(f"{ctx.author.display_name} is no longer afk...")
This is reading a json file that looks like this (replace 000000 with your id):
{
"000000" : "afk",
"someOtherGuy" : "afk"
}
All of this uses dictionaries and the json module. If you're unfamiliar with either of the concepts, here are a few links to help you out :-)
Python Dictionaries,
Python-Json

Related

Trying to check my .JSON file for a users ID

So my plan is to search the JSON file first and check if the user's ID is in there, if it is it should respond with "You have already registered.", if not then it should continue with the rest of the code.(which is where "data" will be added)
So far I only managed to add the "data" to the JSON file but couldn't figure out how to search for the ID eventually deleting the rest of it to find a solution.
#client.command(aliases = ['Register'])
async def register(ctx):
data = ctx.author.id, currency, Class, Cards
with open('Player_Stats.json', 'w') as f:
json.dump(data, f)
await ctx.send("Account registered!")
You should prefer a database query over a JSON file lookup. If you still want to go with the file you should probably detail the file format. Anyway you will load the file and search for the key or value on the JSON.

Discord.py - How can I save data in .json for a specific server?

I need to save a data for a specific server only. How can I do it?
For example to save coins:
def set_coins(member: discord.Member, amount: int):
with open('data/bank.json', 'r') as f:
balance = json.load(f)
balance[str(member.id)] = amount
with open('data/bank.json', 'w') as f:
json.dump(balance, f, indent=4)
As you can see, it saves only member id (for all the servers where it is).
json file can contain another json file.
balance[str(guild.id)][str(member.id)] is what you want.

Python does not identify json dictionary keys and writes it twice. (Discord.py)

I've been trying to open a json file store the items into a variable, modify/add one item, and then dump it back to the json file. This works, but when I open the file again it does not identify the key.
with open("descriptions.json", "r+") as f:
descs = json.load(f)
descs[ctx.guild.id] = desc
with open("descriptions.json", "w+") as f:
json.dump(descs, f)
embed = discord.Embed(
title="Description Set",
description=f"Your server description is set!\n{desc}",
color=0x13f30f
)
await ctx.send(embed=embed)
This is the code at the moment. When I use the command to set a description it works all fine. Using it again will NOT replace the value of the key (which in this case is the id of the server), but create another key with the same name and put the description there. Note that even if I use the same description, it will still not work.
Using it for the first time
{"452945790697078785": "Test Description"}
Using it for the second time
{"452945790697078785": "Test Description", 452945790697078785: "Test Description"}
Basically using print(repr(list(descs.keys()))) showed me that one key was an integer and the other key was a string. Therefore, converting the ctx.guild.id to a string fixed the problem.
with open("descriptions.json", "r+") as f:
descs = json.load(f)
descs[str(ctx.guild.id)] = desc
print(repr(list(descs.keys())))
with open("descriptions.json", "w+") as f:
json.dump(descs, f)
embed = discord.Embed(title="Description Set",
description=f"Your server description is set!\n{desc}",
color=0x13f30f)
await ctx.send(embed=embed)

Parsing tweets' text out of "Status" wrapper in json file

I used this tweepy-based code to pull the tweets of a given user by user_id. I then saved a list of all tweets of a given user (alltweets) to a json file as follows. Note that without "repr", i wasn't able to dump the alltweets list into json file. The code worked as expected
with open(os.path.join(output_file_path,'%s_tweets.json' % user_id), 'a') as f:
json.dump(repr(alltweets), f)
However, I have a side problem with retrieving the tweets after saving them to the json file. I need to access the text in each tweet, but I'm not sure how to deal with the "Status" wrapper that tweepy uses (See a sample of the json file attached).sample json file content
I tried to iterate over the lines in the file as follows, but the file is being seen as a single line.
with open(fname, 'r') as f:
for line in f:
tweet = json.loads(line)
I also tried to iterate over statuses after reading the json file as a string, as follows, but iteration rather takes place on the individual characters in the json file.
with open(fname, 'r') as f:
x = f.read()
for status in x:
"""code"""
Maybe not the prettiest solution but you could just declare Status as a dict and then eval the list (the whole content of the files).
Status = dict
f = open(fname, 'r')
data = eval(f.read())
f.close()
for status in data:
""" do your stuff"""

How to add a key-value to JSON data retrieved from a file?

I am new to Python and I am playing with JSON data. I would like to retrieve the JSON data from a file and add to that data a JSON key-value "on the fly".
That is, my json_file contains JSON data as-like the following:
{"key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
I would like to add the "ADDED_KEY": "ADDED_VALUE" key-value part to the above data so to use the following JSON in my script:
{"ADDED_KEY": "ADDED_VALUE", "key1": {"key1A": ["value1", "value2"], "key1B": {"key1B1": "value3"}}}
I am trying to write something as-like the following in order to accomplish the above:
import json
json_data = open(json_file)
json_decoded = json.load(json_data)
# What I have to make here?!
json_data.close()
Your json_decoded object is a Python dictionary; you can simply add your key to that, then re-encode and rewrite the file:
import json
with open(json_file) as json_file:
json_decoded = json.load(json_file)
json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
with open(json_file, 'w') as json_file:
json.dump(json_decoded, json_file)
I used the open file objects as context managers here (with the with statement) so Python automatically closes the file when done.
Json returned from json.loads() behave just like native python lists/dictionaries:
import json
with open("your_json_file.txt", 'r') as f:
data = json.loads(f.read()) #data becomes a dictionary
#do things with data here
data['ADDED_KEY'] = 'ADDED_VALUE'
#and then just write the data back on the file
with open("your_json_file.txt", 'w') as f:
f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
#I added some options for pretty printing, play around with them!
For more info check out the official doc
You can do
json_decoded['ADDED_KEY'] = 'ADDED_VALUE'
OR
json_decoded.update({"ADDED_KEY":"ADDED_VALUE"})
which works nicely if you want to add more than one key/value pair.
Of course, you may want to check for the existence of ADDED_KEY first - depends on your needs.
AND I assume you want might want to save that data back to the file
json.dump(json_decoded, open(json_file,'w'))

Categories

Resources