IndexError: list assignment index out of range [python + json]

Question:

The error in the title is given to me when I try to use a command in discord.py the command is !sell my code:

if "!sell" in message.content:
    
    Rndm_mon = (random.randrange(1000,5000))
    with open('income.json', 'r') as f:
            h = [json.load(f)]

            

            entry = h[(len(f'| {message.author.name} '))] = (Rndm_mon)

            h.append(entry)

    with open('income.json', 'w') as f:
            json.dump(h, f, indent=4)

            saveJson(h, "income.json")

    await message.channel.send('You Earned ' + Rndm_mon + ' Dollars from selling')

the error is IndexError: list assignment index out of range and cites this part for the issue how do i fix this error?
entry = h[(len(f’| {message.author.name} ‘))] = (Rndm_mon)

the code is supposed to generate a random number, then add that number to a json file and then add up the previous value in the json file with the new one and in the end have a final value of the old balance and new money added together for a sort of banking system

my income.json file looks like this

{
    "| name ": "1716",
    "| name_1 ": "4291",
    "| name_2 ": "4778",
    "| name_3 ": "1254"
}
Asked By: SF Mittens

||

Answers:

It’s probably easier to work this out via an answer.

This works for a JSON file where your values are numeric. In your version they’re strings but that would make the solution a little more difficult to work with since you’d have to convert strings to numbers in order to do math on them.

For example, this is what the JSON should look like, and what Python’s json module will try to write by default since you basically have a mapping of str: int for your dict keys.

{
    "| name ": 1716,
    "| name_1 ": 4291,
    "| name_2 ": 4778,
    "| name_3 ": 1254
}

Now, here’s a version of your code that probably does what you want based on what we discussed in the comments.

Notice that there are some changes to how everything is loaded and modified.

if "!sell" in message.content:
    k = f"| {message.author.name} "
    val = random.randrange(1000, 5000)

    # open entire file for reading and writing
    with open("income.json", "r+") as f:
        incomes = json.load(f)

        # Either add the value to the user's balance
        # or, if they don't exist yet, create the entry
        # with the val
        try:
            incomes[k] += val
        except KeyError:
            incomes[k] = val

        # seek to beginning and rewrite file
        f.seek(0)
        json.dump(incomes, f, indent=4)
        f.truncate()

    await message.channel.send(f"You Earned {val} Dollars from selling")


If you need to convert your JSON file…

import json

with open("income.json", "r+") as f:
    d = json.load(f)
    n = {k: int(v) for k, v in d.items()}
    f.seek(0)
    json.dump(n, f, indent=4)
    f.truncate()
Answered By: wkl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.