Home > front end >  Creating and retrieving data in JSON format
Creating and retrieving data in JSON format

Time:12-19

I am making a program that allows you gamble and it creates an object of the player with attributes like current money, how many wins/losses the player has etc..

I am currently able to have this working and the information is saved while the program is running, however I want to implement a feature that allows me to save this user information in a json and then next time the program is run, check that json to see if the name entered by the player matches any value for 'name' in the json and pull their profile from when they last played.

Currently I am learning how to read/write json data and I am able to get data saved to a json, but I'm unable to save it in the format that I want and retrieve it later and convert the data back into my object with attributes.. Specifically I can save the user like this:

import json

class Casino:
    def __init__(self, name, money, wins, debt):
        self.name = str(name)
        self.money = int(money)
        self.wins = int(wins)
        self.debt = int(debt)
        self.is_gambling = True
        self.losses = 0

    def add_win(self):
        self.wins = self.wins   1

    def add_loss(self):
        self.losses = self.losses   1

    def add_money(self, bet: int):
        self.money = self.money   bet

    def add_debt(self, debt: int):
        if self.money == 0:
            print("You have gone into debt..")
            print("Your debt has gone up")
            self.debt = self.debt   debt
        else:
            print("Your debt has gone up")
            self.debt = self.debt   debt

    def change_name(self, newname):
        self.name = newname
        return self.name

    def indebt(self):
        if self.debt > 0:
            print('You are in debt..')
            print(f'You owe ${self.debt}')
        else:
            print('You are not in debt')

    def addrep(self, rep: int):
        self.reputation = self.reputation   rep
        return self.reputation

    def remrep(self, rep: int):
        self.reputation = self.reputation - rep
        return self.reputation


player2 = {
    'name': 'dolorean',
    'money': 0,
    'wins': 0,
    'debt': 0
}

show = json.dumps(player2)

with open('test.json', 'w') as userfile:
    json.dump(show, userfile)

and it will save to the json like this:

"{\"name\": \"dolorean\", \"money\": 0, \"wins\": 0, \"debt\": 0}"

But I want to retrieve the attributes by the name of the user.

Do I need to create a nested list of some sort in the json? And if I do how do I do that? I have tried changing my player variable from:

player2 = {
        'name': 'dolorean',
        'money': 0,
        'wins': 0,
        'debt': 0
}

to:

player2 = {
           'users': {
               'name': 'dolorean',
               'money': 0,
               'wins': 0,
               'debt': 0
         }
}

But I'm unsure of how to retrieve the data so it just saves it in a way that looks different to me..

CodePudding user response:

This data structure will allow many different player names:

{
    "jim": {"money": 100, "wins": 5, "debt": 0},
    "betty": {"money": 200, "wins": 7, "debt": 5}
}

CodePudding user response:

Okay so my solution from martineau's comment was to do this:

I will generate a name using the input function (only temporary, I am adding this to a discord bot so eventually the name will be their server display name and their file name will be their unique server id so I can save their info to their file) and I make following object from that input and convert it into json format then convert it back.

gam_name = str(input('What is your name?'))
player1 = Casino(gam_name, 500, 0, 0)

player1 = {

        'name': gam_name,
        'money': player1.money,
        'wins': player1.wins,
        'debt': player1.debt
}

with open(gam_name   '.json', 'w') as userfile:
    json.dump(player1, userfile)


with open(gam_name   '.json') as userfile:
    info = json.load(userfile)
    print(info['name'])
    print(info['money'])
    print(info['wins'])
    print(info['debt'])

Now this way I can save each value to whatever it currently is and I can just run that whenever they win or lose it will overwrite their current values with the new ones and then just close the file when it's done using the with statement.

This is exactly what I was trying to do, now I can call the info from the unique file specific to the player and it will allow two people to have the same display name or username with different information.

Thank you for the help!

  • Related