I have an users.json file which store the user’s id and lmessage
(current date,time) if he is write in a room.
JavaScript
x
2
1
{"5314934047066510132": {"lmessage": "2021-04-21 10:21:01"}}
2
How can I get all of these IDs and the lmessage
s which belongs to that ID without specify username or anything?
Currently I can get the user’s lmessage
with a command if I specify the username:
JavaScript
1
8
1
@client.command()
2
async def lastmess(ctx, member: discord.Member = None):
3
id = member.id
4
with open('users.json', 'r') as f:
5
users = json.load(f)
6
lastmessage = users[str(id)]['lmessage']
7
await ctx.send(f'{member} Last message: {lastmessage}!')
8
Advertisement
Answer
If I understand your question correctly, you just want to iterate through all of the key-value pairs in the JSON data. If so, you can use the various dictionary methods available:
JavaScript
1
15
15
1
with open("users.json") as file:
2
data = json.load(file)
3
4
# Get all keys (user IDs)
5
user_ids = list(data.keys()) # OR list(data)
6
7
# Get all values (last message dictionary)
8
last_messages = list(data.values())
9
10
# Get all keys and values tuples
11
ids_and_last_messages = list(data.items())
12
13
# Get all last message dates
14
last_message_dates = [uid["lmessage"] for uid in data.values()]
15