Json.dump does not append my data correctly

here’s the code for the file writer:

def createAccount():
    while True:
        username = input("Create your username: ")
        password = input("Create your password: ")
        if username.isspace() == True or password.isspace() == True and len(username) <= 3 or len(password) < 10:
            print("the username or password does not meet the requirements. Please try again.")
            continue
        break

    userid = random.randint(1000000, 9999999)

    Udata = {
            username:
                {
                    "userid": userid
                }
        }

    data = {
        "password": password,

        "last_logged_in": 0,
        "high_score": 0,
        "rage_quit_last_time": False
    }


    json.dump(Udata, open(accountsDir, 'a'), indent=3)
    os.makedirs("accounting/UserData/" + str(userid), exist_ok=True)

    open("accounting/UserData/" + str(userid) + "/data.json", "w")
    open("accounting/UserData/" + str(userid) + "/scores.json", "w")

    scoresFile = "accounting/UserData/" + str(userid) + "/scores.json"
    Datafile   = "accounting/UserData/" + str(userid) + "/data.json"

    json.dump(data, open(Datafile, 'w'), indent=3)

    print("Account Created. your username is: ", username + ". You can now play the fukin game.")
    return username, password

and the json file after 2 accounts have been made.

{
   "test1": {
      "userid": 9146500
   }
}{ //why do this?
   "test2": {
      "userid": 7593340
   }
}

Separate, unrelated calls to json.dump won’t “combine” anything if you append to an existing file. You will need to read in the old JSON data, and append the new data in whatever way is appropriate in Python (e.g. in a list or something), then overwrite the old data file with a new call to json.dump that has all the data already combined.

2 Likes

thanks! wow thats going to be annoying to fix lol

Well, you don’t need to do it that way. You could use a record oriented
file and just append new records. There’s a common JSON based format
called newline-delimited JSON (it’s got another name too, commonly, but
I can’t recall it because my brain is full). It is just a text file with
records, one per line, each line a complete piece of JSON.

Using your example, it would want to look like this:

 { "test1": { "userid": 9146500 } }
 { "test2": { "userid": 7593340 } }

The appending a record is as simple as:

 with open(filename, 'a') as f:
     print(json.dumps(your_record, separators=(',', ':')), file=f)

Naturally you’ll need to read it all back as records when you load the
file.

2 Likes

https://jsonlines.org/

2 Likes