I have what I think is a bit more difficult "problem" to solve today. In my script, I have a function which reads out a corresponding translation/record from a JSON for each executed command.
The function looks like this:
response_string = {} # Gets the correct JSON from my JSON structure and reads out the correct message
def get_lang(guild, response):
try:
with open("languages.json", "r") as f: # Open the JSON to see which language the guild chose
data = json.load(f)
return response_string[data[str(guild)]][response] # Get response from the corresponding JSON for the guild
except:
return response_string['english'][response] # If not set it is English
But here is the concern, that the JSON file is always open. This could become an issue in the end, I have been told. The JSON structure from which I get the responses looks like this:
./languages # Folder
./languages/german.json
./languages/english.json
...
In a JSON it looks like this:
{
"all_langs": "Available Languages"
}
Say, for each language, there is a translation in each JSON. When running a command, I would then always call get_lang, "all_langs".
I was told that it would be smart to convert the JSON to a dict and then read out all the translations when starting the application, so you don't always have to have the JSON open. Is this a common or better practice?
I have already looked at the following articles:
- Python open json file keep in memory
- Open and read latest json file one time only
- How to save a list to a file and read it as a list type?
I also started and thought about how to handle this.
client.languages_loaded = False # Set it to False
@client.event
async def on_ready():
print("Online")
if client.languages_loaded:
return
client.languages_loaded = True
client.languages = # Define all the JSON's here or start to store it in a dict?
But unfortunately I can't get any further, I'm more or less at the end with the knowledge, because in the end I don't know how the readout should always work without keeping the JSON open. About any tip I am grateful!
UPDATE: The code I use to get the correct language JSON is the following:
for i in os.listdir('./languages'):
if i.endswith('.json'):
with open(os.path.join('./languages', i)) as file: # Always open
response = json.load(file) # Get the response from the correct JSON
response_string[i.replace(".json", "")] = response # Give out response