Reputation: 47
Hello stackoverflows users,
I'm learning python and writing/reading in json file
I want to make a logging system with discord.py that captures all messages, writes them in a json file, and when a command is executed, retrieve the data, filter with the user parameters and return the filtered data.
The problem is that i can't write json files with a good structure, currently my structure is looking like this currently :
{
"Messages": [
{
"Guild_id": 831900150115991605,
"User_id": 225282512438558720,
"User_name": "JsuisEnPeignoir",
"Message": "Yo!"
},
{
"Guild_id": 831900150115991605,
"User_id": 225282512438558720,
"User_name": "JsuisEnPeignoir",
"Message": "Hello, my friend!"
}
]
}
But i want to do something like this :
{
"Messages": [
831900150115991605 : [ <- guild_id
225282512438558720 : [ <- user_id
"User_name": "JsuisEnPeignoir",
"Message": "Yo!"
]]
},
}
(this is approximate)
Currently my code is this :
with open('debug_data.json', 'r') as filename:
data = json.load(filename)
data['Messages'].append({
'Guild_id' : ctx.guild.id,
'User_id' : ctx.author.id,
'User_name' : ctx.author.name,
'Message' : ctx.message.content[8:2000]
})
with open('debug_data.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
What code should i write to get the structure as i shown ?
Upvotes: -1
Views: 601
Reputation: 806
In your code exemple, you have a bracket missing, so I assume what you wanted is this kind of json structure
{
"Messages": {
831900150115991605 : {
225282512438558720 : {
[{"User_name": "JsuisEnPeignoir", "Message": "Yo!"}, {"User_name": "JsuisEnPeignoirModifié", "Message": "Un autre message"}]
},
225282512438558721 : {
[{"User_name" : "MissingBracket", "Message": "There is a missing bracket in your exemple"}]
}
}
}
}
The best practice in my opinion with JSON in Python is when you read your data, always check if the key is inside, if not, you add it with the default value (in this case, an empty dict or empty list).
Here's how I'd do it
with open('debug_data.json', 'r') as filename:
data = json.load(filename)
if ctx.guild.id not in data["Messages"]:
data["Messages"].append({ctx.guild.id: []})
if ctx.author.id not in data["Messages"][ctx.guild.id]:
data["Messages"][ctx.guild.id].append({ctx.author.id: []})
data["Messages"][ctx.guilld.id][ctx.author.id].append({"User_name": ctx.author.display_name, "Message": ctx.message.content})
with open('debug_data.json', 'w') as outfile:
json.dump(data, outfile, indent=4)
Upvotes: 1