Using a dict from JSON doesn't work properly

Question:
How can I use a dict after reading it from JSON?

Repl link:
https://replit.com/@R9Gaming/Maxim-Bot

import discord
from discord.ext import commands
import os
import simplejson as json
message_count = {}
levels = {}

TOKEN = os.getenv("DISCORD_TOKEN")
intents = discord.Intents.all()
client = discord.Bot(intents=intents, activity=discord.Game(name='a random game'))


@client.event
async def on_ready():
  print(f'{client.user} Welcome to Discord!')
  with open("levels", "r") as i:
    message_count = json.loads(i.readlines()[0], strict=False)
    print(message_count['r9_dev'])

@client.slash_command(name="ban")
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member):
  await member.ban()

@client.event
async def on_message(message: discord.Message):
    index=f"{message.author.name}"
    if not message.author.name in message_count.keys(): message_count[index] = 1
    else: message_count[index]+=1
    print(f"Received {message.content} from {message_count}, count: {message_count[index]}")
    with open("levels", "w") as outfile:
      json.dump(message_count, outfile)
client.run(TOKEN)

You can use a dict read from JSON like any other normal dict. Hope this helps!

That is the problem. I can’t write on the dict after getting it from a JSON file

Print the dictionary, screenshot it and send it here.

The dict: {'r9_dev': 1}

I don’t think you’re supposed to be able to write on the dictionary.

I think that dicts read from JSON are read-only.

Maybe do

theVarName = dict(theVarName)

?

I’m surprised nobody else has given adequate help, but let me assist you.

First of all, use the standard JSON library instead of simplejson. Here’s an example:

import json

# Interpret JSON to dict
json.loads()

# Interpret dict to JSON
json.dumps()

Next, depending on what you’re asking, you can modify an elements value within a dict like this:

dictionary = {"exampleValue": True}
print(dictionary["exampleValue"])
# Outputs 'True'
dictionary["exampleValue"] = False # Set value
print(dictionary["exampleValue"])
# Outputs 'False'
# GET DICT VALUE
dictionary["exampleValue"]
# OR
dictionary.get("exampleValue")

# SET DICT VALUE
dictionary["exampleValue"] = "newValue"

The difference between dict[] and dict.get() is with dict[] if a value is not found it will raise an error. With dict.get(), if a value is not found it will just return None.

Now, assuming you want to update the file to any new values, you can do so like this:

dictionary = {"exampleValue": "newValue"}
file = open("file.txt", "w")
file.write(dictionary) # Write the new content to the file
file.close()
6 Likes

Instead of that, you should use

with open("file.txt", "w") as file:
    file.write(dictionary)
5 Likes

I will try this one.