Search code examples
pythonjsonvariablesencoding

How to encode a dictionary then write it to a file then decode it to then set it as variables?


So, I am creating a game where there are some variables like: Have they got x paper, have they done this room, what they have in their inventory. As seen here: Code1 And then lets say I then restart the game, it checks if there is any data in the file, if not it creates the variables (this isn't important) but if so it will load them as seen here: Code2 And this is what the json file looks like:

{"hd1": true, "hd2": true, "hd3": false, "hd4": false, "hd5": false, "P1": "Unlocked", "P2": "Unlocked", "P3": "Unlocked", "P4": "Locked", "P5": "Locked", "Inv": ["Killed my wife, my name is John. \n John created the safe // The code to the SAFE is 728 and the code to the LOCK is 1538 // Born on the 6th of November", "If you have found this letter, good, help me, I think I have gone south to the nearby yellow tree, PLEASE HELP!! \n Suit of Sir John the Great // The sky seems blue today, I'm wearing a red coat and some cargo green trousers, the sun looks more yellow today too"]}

In theory, what I want to do is somehow encode this in base64, then decode it to then read it as a json to then reload the save data.

Here's a concise way of putting it:

Variables encoded --> store in file --> Reads and decodes it --> loads the variables

NOTE: I do have a list called "Inventory" as seen.


Solution

  • Use the base64 library along with the string variants of json.dump and json.load.

    import base64, json
    
    def save():
        dictionary = { ... }
        with open("save.dat", "wb") as outfile:
            outfile.write(base64.b64encode(json.dumps(dictionary).encode()))
    

    When you reload it you use:

    with open("save.dat", "rb") as infile:
        dictionary = json.loads(base64.b64decode(infile.read()))