G
G
gooze2019-07-22 20:52:02
Python
gooze, 2019-07-22 20:52:02

JSON Keys in the dictionary are duplicated for some reason?

I had this problem several times, each time I found a solution, but then I encounter it again. This time I can't figure out what the problem is anymore.
I will be glad if you tell me.
I make a chat bot, write user data to a file, and read the data from there once during the bot launch. I use json library, python3.
Keys begin to be duplicated after the first write to the file.
This is how I read from a file:

def reloadz():
    global users, payments
    try:
        with open(path + 'data.json', 'r', encoding='utf-8') as f:
            datz = json.loads(f.read())
            
            users = datz['users']
            payments = datz['payments']
            
            print(datz)
    except:
        with open(path + 'data.json', 'w') as f:
            f.write(json.dumps({'users': {}, 'payments': []}))
        users = {}
        payments = []

reloadz()

While the bot is running, I change the `users` and `payments` variables. At the end of each iteration, I write back to the file
with open(path + 'data.json', 'w') as f:
    f.write(json.dumps({'users': users, 'payments': payments}))

As a result, after the first iteration, two identical keys appear in the dictionary in the file. Here is an example of what is obtained in the file:
{"users": {"603660417": {"sub": false, "current_menu": "main"}, "603660417": {"sub": true, "current_menu": "sub"}}, "payments": [16019644137]}

I think it's the second day! I do not know what to do. Tell!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Taus, 2019-07-22
@Taus

It is very likely that somewhere else in your code you are adding values ​​to usersboth by int-key and str-key. Solution: move to one notation everywhere.

import json
d = {123: 'a', '123': 'b'}
json.dumps(d) # '{"123": "a", "123": "b"}'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question